最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - show div for a set time, then hide it - Stack Overflow

programmeradmin5浏览0评论

Im using jquery for various things on my site, but one thing im not sure how to do, is have it show an element, then wait X seconds, and hide the element.

$('#form').ajaxForm(function() { 
    $('#cartcontents').fadeOut("fast").load('cart.php').fadeIn("fast");
}); 

That's the JavaScript that I'm using now. How could I have it (when the form submits) display the div #notice for 5 seconds, then fadeOut?

Im using jquery for various things on my site, but one thing im not sure how to do, is have it show an element, then wait X seconds, and hide the element.

$('#form').ajaxForm(function() { 
    $('#cartcontents').fadeOut("fast").load('cart.php').fadeIn("fast");
}); 

That's the JavaScript that I'm using now. How could I have it (when the form submits) display the div #notice for 5 seconds, then fadeOut?

Share Improve this question edited Dec 26, 2010 at 3:43 Jacob Relkin 163k33 gold badges351 silver badges321 bronze badges asked Dec 9, 2009 at 10:07 mrpatgmrpatg 10.1k44 gold badges113 silver badges169 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 19
$('#form').submit(function() {
   $('#notice').show();
   setTimeout(function() { 
       $('#notice').fadeOut(); 
   }, 5000);
});

in the onSubmit event handler make the div appear by using $('#divName').show() (i think thats correct syntax). The you can use setTimeout("hideDiv()",5000), you then define hideDiv() which is a new function which does $('#divName').fadeOut()

As jQuery is not so popular nowadays. Here is a simple solution with vanilla JavaScript.

const notification = document.querySelector("#notification");
const button = document.querySelector("#button");
button.addEventListener("click", ()=>{
  notification.style.display = "block";
  setTimeout(()=>{notification.style.display="none"},5000);
});
<div id="notification" style="display:none;">
    <p>You clicked the button. Wait for 5 seconds now. </p>
</div>

<button id="button">Click Me to Display </button>

You set the default style to none and change when the button is clicked.

发布评论

评论列表(0)

  1. 暂无评论