check if this element OR this element is hovered with jQuery

14,550

Solution 1

It works, you're just running it on page load, not when the mouse moves

$(document).mousemove(function() {    
    if($('#elm1').is(':hover') || $('#elm2').is(':hover')) {
        // Do stuff
    }
    else {
        // Revert do stuff or do other stuff
    }
});

Example here

But, as other's have said, jQuery already knows the hover state, so doing it this way would be unnecessary. In practice you should use the same selector to apply the function to it

$('#idOne, #idTwo').hover(function() { /* Do stuff */ });

Solution 2

I would register events on mouseover and whenever the event happens trigger a function

$("#elm1, #elm2").on("mouseover", function () {
    // effect here
});

Solution 3

Why not simply add the handler to both elements like this :

$('#elm1, #elm2').hover(function(){
     // ... do stuff here ...
});

Should work . . .

Share:
14,550
Ty Bailey
Author by

Ty Bailey

Full stack developer specializing in PHP/MySQL Web Applications and React Native mobile applications.

Updated on June 05, 2022

Comments

  • Ty Bailey
    Ty Bailey almost 2 years

    I have two separate elements in my DOM that require a change when either one is hovered. When the link is hovered, the image src needs to change (easy) AND the link color needs to change. When the image is hovered, the same effect needs to happen (image src changes & link color changes)

    This is actually quite easy to do, but I have a feeling there is a MUCH easier way to do it then the approach I am taking. Currently I am going through each of the 8 elements and testing if they are hovered individually. This works good, but there is so much more jQuery here than I feel there should be.

    I tried adding the attribute onmouseover to both of the elements and triggering the same function, but for some reason the function wasn't triggering.

    Is there a way to test if either element is hovered and trigger a function if either one is? Something like this:

    if($(#elm1).hover() || $('#elm2').hover()) {
        //effect here
    }
    

    OR

    if($('#elm1').is(':hover') || $('#elm2').is(':hover')) {
        //effect here
    }
    

    I tried my example code above, but wasn't getting any results. Is there a way to do this or am I stuck with checking each individual element?