Wednesday 23 October 2019

javascript - Pass $(this) into setTimeout function in mouseover




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!


Answer



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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...