简体   繁体   中英

How would I add a delay to this JQuery event?

This is an event that appends some html:

   $("#feed").live("mouseover", function(){
       $("#main").append('<div class="help_div" id="feed_help"><p>Your feed shows you information on the users you follow, such as songs added, voting, commenting, following, and the showing of songs between users.</p></div><div class="arrow" id="feed_arrow"></div>');
    });

How would I cause there to be a 2000 millisecond gap between mousing over the selected element and appending the html?

You'll use a timeout.

$("#feed")
    .live("mouseover", function() {
        $(this).data("timeout", setTimeout(function() {
            $("#main").append('<div class="help_div" id="feed_help"><p>Your feed shows you information on the users you follow, such as songs added, voting, commenting, following, and the showing of songs between users.</p></div><div class="arrow" id="feed_arrow"></div>');    
        }, 2000));
    });

That will wait 2 seconds before running the code but if you move the mouse out of the element it will still show up 2 seconds later. So what you do is that you add a clearTimeout event. That will make sure that the timeout doesn't tick if you're not hovering.

$("#feed")
    .live("mouseout", function() {
        var timer = $(this).data("timeout");
        if (timer)
            clearTimeout(timer);
    });

You can also use delay method .

This method was added in JQuery 1.4
Using this, your code will become:

$("#feed").live("mouseover", function(){
       $("#main").delay(2000).append('<div class="help_div" id="feed_help"><p>Your feed shows you information on the users you follow, such as songs added, voting, commenting, following, and the showing of songs between users.</p></div><div class="arrow" id="feed_arrow"></div>');
    });

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM