Reputation: 2432
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?
Upvotes: 3
Views: 14829
Reputation: 610
I would register events on mouseover and whenever the event happens trigger a function
$("#elm1, #elm2").on("mouseover", function () {
// effect here
});
Upvotes: 3
Reputation: 3299
Why not simply add the handler to both elements like this :
$('#elm1, #elm2').hover(function(){
// ... do stuff here ...
});
Should work . . .
Upvotes: 2
Reputation: 26014
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
}
});
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 */ });
Upvotes: 8