简体   繁体   中英

jQuery How to make a popup Appears / Disappears on timer?

When my website loads, the popup appears - I need to make it automatically close after a specific time.

$(document).ready(function () {

    //select the POPUP FRAME and show it

    $("#popup").hide().fadeIn(1000);

    //close the POPUP if the button with id="close" is clicked
    $("#close").on("click", function (e) {
        e.preventDefault();
        $("#popup").fadeOut(1000);
    });

}); 

There is already a button but i need to remove it.

You can use the delay() function for that:

 $(document).ready(function() { $("#popup").hide().fadeIn(1000).delay(5000).fadeOut(1000); $("#close").on("click", function(e) { e.preventDefault(); $("#popup").fadeOut(1000); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="popup">popup</div> 

Please mind the note that is given on the documentation:

The .delay() method is best for delaying between queued jQuery effects. Because it is limited—it doesn't, for example, offer a way to cancel the delay—.delay() is not a replacement for JavaScript's native setTimeout function, which may be more appropriate for certain use cases.

Javascript have option setTimeout .setTimeout is a native JavaScript function (although it can be used with a library such as jQuery, as we'll see later on), which calls a function or executes a code snippet after a specified delay (in milliseconds).

setTimeout(function() {
      $("#popup").fadeOut(1000);
 }, 1000);

or in jquery use .delay() . Set a timer to delay execution of subsequent items in the queue.

$("#popup").delay(1000).fadeOut(1000);

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