20

i want to add a div and after 5 seconds remove it. i tried

$("#mainContentTD").prepend("<div style='color: #038a00; padding-bottom:10px;'>Your detailes where sucsesfuly... </div>").delay(5000).remove("this:first-child");
eyalb
  • 2,994
  • 9
  • 43
  • 64

3 Answers3

47

You can use setTimeout like this:

setTimeout(function(){
  $('#divID').remove();
}, 5000);

The 5000 (ms) means 5 seconds. You should replace divID with your own div/element id.

You can make sure that the div exists first using length:

setTimeout(function(){
  if ($('#divID').length > 0) {
    $('#divID').remove();
  }
}, 5000)
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • 2
    Its worth noting that the check for the div existence is entirely unnecessary as jQuery will not error when calling $.fn.remove() on an empty jQuery collection. – tbranyen Apr 06 '11 at 07:25
10

The .delay() method only works with methods that utilize the standard effect queue or a custom queue.

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.

I.e., you could either use setTimeout(): (Demo)

var $elm = $("<div style='color: #038a00; padding-bottom:10px;'>Your detailes where sucsesfuly... </div>");
$("#mainContentTD").prepend($elm);
setTimeout(function() {
    $elm.remove();
}, 5000);

Or, you could use a effect method to remove to element: (Demo)

$("#mainContentTD")
    .prepend("<div style='color: #038a00; padding-bottom:10px;'>Your detailes where sucsesfuly... </div>")
    .children(':first')
    .delay(5000)
    .fadeOut(100);
jensgram
  • 31,109
  • 6
  • 81
  • 98
0

You can try this code, In my case it worked nicely.

setTimeout(function () {
    document.getElementById('not-valide').style.display = 'none'
    document.getElementById('valide').style.display = 'none'
}, 5000)