I am designing a mega menu and wanted to update image inside a div according to the link being hovered upon. What I am trying to do is put a wait for the mouseleave part of the code so that if the user moves instantly to the next LI tag, the mouseleave part of the code is not executed. But if the user does not mouseenter another LI for 2 seconds, then this mouseleave code is executed.
The problem is that #1 returns the value alright, but #2 gives an 'undefined' value. Why is that and how can I fix that? How can I fetch the attr of the current LI being hovered INSIDE the setTimeout function? Since once I have the value, I can do a comparison to control the flow. Thanks a lot.
// FADE IN THE IMAGE ACCORDING TO THE MENU ITEM
// HTML=<li><a data-pos="left -256px" href="somelink">Link A</a></li>
var $sprite = $('#photo');
$('li>a').hover(
function() {
sprite_pos=$(this).attr('data-pos'); // fetch value for the tag
// Put an if otherwise this code gets executes for all li>a creating an unnecessary fade-in out effect
if(typeof(sprite_pos) != "undefined") {
$sprite.fadeTo(200, 0, function() {
$sprite.css("background-position",sprite_pos); });
$sprite.fadeTo(200, 1);
}
},
function() {
//sprite_pos=$(this).attr('data-pos'); // #1
setTimeout( function() {
sprite_pos=$(this).attr('data-pos'); // #2 fetch value for the tag
if(typeof(sprite_pos) != "undefined" ) {
$sprite.fadeTo(200, 0, function() {
$sprite.css("background-position",default_pos); });
$sprite.fadeTo(200, 1);
} // if(typeof(sprite_pos) != "und ...
}, 2000 );
}
); // $('li>a').hover( ...
When setTimeout
is called this
becomes the window
object. To fix simply create a reference to the original this
context:
function() {
var me = this;
setTimeout( function() {
sprite_pos=$(me).attr('data-pos'); // #2 fetch value for the tag
/// ^^
/// ... rest of code
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.