7

I am trying to show a div of information on a bar graph if the user hovers over the bar for a second. The answers on this site have gotten me to this point

var timer;
$(".session_hover").on({
     'mouseover': function () {
          timer = setTimeout(function () {
              $(this).children('.session_info').css({'top':175,'right':20}).fadeIn('fast');
          }, 1000);
     },
     'mouseout' : function () {
          clearTimeout(timer);
     }
});

The above code works when I replace $(this) with $(".session_hover") but then, of course it triggers all the other $(".session_hover") on the page.

How can I pass $(this) into my setTimeout function so that it only applies to the child element of the div I am hovering over?

Thanks for your help!

Reed Raymond
  • 223
  • 2
  • 12

3 Answers3

10

Try creating a closure around a variable to capture $(this), and then use it in your function:

 'mouseover': function () {
      var $this = $(this);
      timer = setTimeout(function () {
          $this.children('.session_info').css({'top':175,'right':20}).fadeIn('fast');
      }, 1000);
 },

Note that in modern browsers, you can also provide this as a parameter to setTimeout, like this:

 'mouseover': function () {
      timer = setTimeout(function (t) {
          $(t).children('.session_info').css({'top':175,'right':20}).fadeIn('fast');
      }, 1000, this);
 },

However, if you want this to work in IE < 9, you need to use one of the polyfill techniques described in this MDN article.

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
2

You need to hold a reference to this outside the setTimeout.

var timer;
$(".session_hover").on({
     'mouseover': function () {
          var ctx = this;
          timer = setTimeout(function () {
              $(ctx).children('.session_info').css({'top':175,'right':20}).fadeIn('fast');
          }, 1000);
     },
     'mouseout' : function () {
          clearTimeout(timer);
     }
});

Another alternative is to use bind which is part of ECMAScript 5 (IE9+).

var timer;
$(".session_hover").on({
     'mouseover': function () {
          timer = setTimeout((function () {
              $(this).children('.session_info').css({'top':175,'right':20}).fadeIn('fast');
          }).bind(this), 1000);
     },
     'mouseout' : function () {
          clearTimeout(timer);
     }
});

Here's a demo using Bind

Brandon Boone
  • 16,281
  • 4
  • 73
  • 100
2

Like this:

var timer;
$(".session_hover").on({
     var self = this;
     'mouseover': function () {
          timer = setTimeout(function () {
              $(self).children('.session_info').css({'top':175,'right':20}).fadeIn('fast');
          }, 1000);
     },
     'mouseout' : function () {
          clearTimeout(timer);
     }
});
inorganik
  • 24,255
  • 17
  • 90
  • 114