Alex C Alex C - 4 months ago 46
Javascript Question

JQuery trigger hover won't work with :not(:hover)

I have a case very similar to this one: https://codepen.io/ianfarb/pen/EJunm

I'm trying to use jquery mouseenter to trigger a hover on the first image which has Id one.

window.setTimeout(function () {
$('#one').trigger('mouseenter');
}, 2500)


However this doesn't appear to work, neither in my code nor in the one in the link above, as :not(:hover) style appears to always be applied. I've also tried with $().offset() to trigger redraw but that won't work either.

Answer

You could use a class to apply the hover styles (using opacity for example)

.image {
  opacity: .5;
}

.image:hover,
.image.is-hover {
  opacity: 1;
}

and then add it in your timeout (and make sure to cleanup the class on real hovers)

jQuery(function($) {
  function enter() {
    $(this).addClass('is-hover').siblings().removeClass('is-hover');
  }

  function leave() {
    $(this).removeClass('is-hover');
  }

  $('.image').hover(enter, leave);

  setTimeout(function() {
    enter.call($('.image:first-child'));
  }, 2500);
});