Search code examples
javascriptcssdelay

show div when clicked and hide again after a couple of seconds


I have this javascript:

function addToCart(id){

    //  alert(document.getElementById('pizza-title'+id).innerHTML);
        document.getElementById('floating-notif').setAttribute("style", "display:block; animation: fadein 2s;-moz-animation: fadein 2s; -webkit-animation: fadein 2s;-o-animation: fadein 2s;");
        setTimeout(hideFloatinDiv(), 5000);
    }

    function hideFloatinDiv(){
        document.getElementById('floating-notif').setAttribute("style", "display:none;");

    }

Now what I am doing is that after a button is clicked the div will show with 2 second transition animation which currently works and after 5 second it will disappear with display none which currently not working.

The problem is that when I put setTimeout(hideFloatinDiv(), 5000); It wont work.

Is there a way to show the div for a couple of second and hide it again in javascript or css?


Solution

  • You're calling the function hideFloatinDiv immediately, instead of passing it to setTimeout. Take off the parentheses:

    setTimeout(hideFLoatinDiv, 5000);