سؤال

I have this code:

jQuery(window).one('load',function() {
    var startopen;
    var startclose;
    var delaytime = 350;
    var togglespeed = 'fast';
    jQuery('.hlp').mouseenter(function() {
        var v = "#" + jQuery(this).parent().parent().attr("id") + " .help";
        if( typeof startclose !== undefined) {
            clearTimeout(startclose);
        }
        startopen = setTimeout(function(){
            jQuery(v).fadeIn(togglespeed);
        }, delaytime);
    }).mouseleave(function(){
        var v = "#" + jQuery(this).parent().parent().attr("id") + " .help";
        if( typeof startopen !== undefined) {
            clearTimeout(startopen);
        }
        startclose = setTimeout(function(){
            jQuery(v).fadeOut(togglespeed);
        }, delaytime);
    });
});

And when the mouse enters .hlp, the .help for that particular parent appears, but not before checking to see if the startclose variable is defined. When the mouse leaves, the function checks if the startopen is defined then sets a timeout for startclose. Pretty straight forward.

My issue is simple: when I mouseenter one .hlp and quickly switch to a nearby .hlp, the startclose from the first .hlp is activated when I mouseleave but then the timeout clears when entering the second .hlp.

I was thinking of making it uniquely identifiable and since my JS is not what I'd like to call AMAZING, I am asking for suggestions to make this code "more better".

Thanks in advance. :)

هل كانت مفيدة؟

المحلول

The idea, expressed by Kevin in comment, is to use a closure to associate specific timer variables to each element.

Change

jQuery('.hlp').mouseenter(function() {
    var v = "#" + jQuery(this).parent().parent().attr("id") + " .help";
    if( typeof startclose !== undefined) {
        clearTimeout(startclose);
    }
    startopen = setTimeout(function(){
        jQuery(v).fadeIn(togglespeed);
    }, delaytime);
}).mouseleave(function(){
    var v = "#" + jQuery(this).parent().parent().attr("id") + " .help";
    if( typeof startopen !== undefined) {
        clearTimeout(startopen);
    }
    startclose = setTimeout(function(){
        jQuery(v).fadeOut(togglespeed);
    }, delaytime);
});

to

jQuery('.hlp').each(function(){
  var startopen, startclose;   
  jQuery(this).mouseenter(function() {
    var v = "#" + jQuery(this).parent().parent().attr("id") + " .help";
    if( typeof startclose !== undefined) {
        clearTimeout(startclose);
    }
    startopen = setTimeout(function(){
        jQuery(v).fadeIn(togglespeed);
    }, delaytime);
  }).mouseleave(function(){
    var v = "#" + jQuery(this).parent().parent().attr("id") + " .help";
    if( typeof startopen !== undefined) {
        clearTimeout(startopen);
    }
    startclose = setTimeout(function(){
        jQuery(v).fadeOut(togglespeed);
    }, delaytime);
  });
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top