Reputation: 426
I'm trying to run hover but only if a given element has certain class.
For exaple:
jQuery
$("#banner").hover(
if ($(this).hasClass("bannerReady")) {
function() {
runOne();
},
function() {
runTwo();
}
}
);
But this won't work.
I've tried using it like this and this will work, but then jQuery won't be aware that the class name was changed in the meantime and it will remain working:
if ($(this).hasClass("bannerReady")) {
$("#banner").hover(
function() {
runOne();
},
function() {
runTwo();
}
);
}
Upvotes: 0
Views: 24
Reputation: 2404
hover()
is just a wrapper method for adding a mouseenter
and mouseleave
handler in one go.
Delegation allows us to attach events to selectors that do not currently exist on the page.
https://learn.jquery.com/events/event-delegation/
$('body').on('mouseenter', '#banner.bannerReady', runOne);
$('body').on('mouseleave', '#banner.bannerReady', runTwo);
By attaching the events to the body (which always exists) and having it delegate for the #banner.bannerReady
selector, you can attach the events the second the page loads, and run them only if the banner actually matches the selector.
If there’s a more specific selector that the banner is in, you can use that instead of body
.
Upvotes: 0
Reputation: 208032
.hover()
expects to receive two functions, so you can't pass an if
statement to it. Change it like this:
$("#banner").hover( function() {
if ( $("#banner").hasClass("bannerReady") ) runOne();
}, function() {
runTwo();
}
});
Upvotes: 1