0

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();
      }
  );
}

2 Answers 2

1

.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();
  }
});
0
0

hover() is just a wrapper method for adding a mouseenter and mouseleave handler in one go.

https://api.jquery.com/hover/

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.