Search code examples
jqueryhtmlcssdelay

Why my object doesn't appear after adding second function in jquery?


I wrote a simple function in jquery which adds css class to my div with photo after clicking on a button.
$('#btn1').click(function(){ $('#div1').addClass('show'});

I want this div (actually it's content) to pop up. CSS:

#div1 {
display: none;
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
max-width: 100%;
max-height: 100%;
margin: auto;
overflow: auto;
}

.show {
display: block!important;  
}

So far works perfectly. But I want this div to dissapear again after 2s so I added this to jquery:

$('#btn1').click(function(){
$('#div1').addClass('show').delay(2000).removeClass('show')
});

And now it doesn't apper at all. So where is my problem? I tried also with setTimeout:

<script>
$('#btn1').click(function(){
$('#div1').addClass('show')
});

setTimeout(function() {
$('#div1').removeClass('show')
}, 2000);
</script>

I'm just starting with programming, so I'll be grateful for possibly easiest to understand code. Thanks for all help.


Solution

  • Use the following. You are actually adding the timeout function outside the button click event. So that actually runs when the page gets loaded and ends before you click the button probably.

    $('#btn1').click(function(){
      $('#div1').addClass('show');
      setTimeout(function(){$('#div1').removeClass('show');},2000);
    });
    

    Hope this helps.