-1

I want to add a delay on this mouseenter shown below. Can anybody help me with this "_on" method, pls? I tried with setTimeout, but it won't work.

This is the code:

declareEvents: function () {   
                var me = this,
                $el;

                $.each(me._$listItems, function (i, el) {
                    $el = $(el);    
                me._on($el, 'mouseenter', $.proxy(me.onListItemEnter, me, i, $el));
},

What I've tried:

setTimeout(function() {
    me._on($el, 'mouseenter', $.proxy(me.onListItemEnter, me, i, $el));
}, 1000);

And:

me._on($el, 'mouseenter', setTimeout(function() {
    $.proxy(me.onListItemEnter, me, i, $el);
}, 1000);

Thank you very much for you help!

2 Answers2

3

You should wrap handler in anonymous function and clear any previous timeout:

me._on($el, 'mouseenter', function () {
    clearTimeout($(this).data('timeout'));
    $(this).data('timeout' , setTimeout(function () {
        $.proxy(me.onListItemEnter, me, i, $el);
    }, 1000));
});

And maybe clear timeout on mouseleave too.

A. Wolff
  • 74,033
  • 9
  • 94
  • 155
1

jQuery UI's code has an example of setting multiple events using _on in a widget. This will allow you to easily remove the timeout on mouseleave, as A. Wolff suggested.

declareEvents: function() {
  var me = this;

  $.each(me._$listItems, function(i, el) {
    var $el = $(el);
    clearTimeout($el.data("hoverTimeout"));

    me._on($el, {
      mouseenter: function () {
        $el.data("hoverTimeout", setTimeout($.proxy(me.onListItemEnter, me, i, $el)));
      },
      mouseleave: function () {
        clearTimeout($el.data("hoverTimeout"));
      },
    });

  });
}
redbmk
  • 4,687
  • 3
  • 25
  • 49