Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying a loading gif for 5 seconds automatically

Tags:

javascript

I want to display a loading gif automatically when the user goes to the website and then after 5 seconds it goes away.

I found this script which does what I want, but it does not do it automatically. The user needs to click on the button to start it which kind of defeats the purpose.

<input type = "button" value = "Show image for 5 seconds" onclick = "show()"><br><br>
<div id = "myDiv" style="display:none"><img id = "myImage" src = "images/ajax-loader.gif"></div><br>

<script type = "text/javascript">

function show() {
    document.getElementById("myDiv").style.display="block";
    setTimeout("hide()", 5000);  // 5 seconds
}

function hide() {
    document.getElementById("myDiv").style.display="none";
}

</script>

If there is any way in which I can do this, or if there is a better way of doing it please just comment.

like image 537
connor.p Avatar asked Dec 23 '11 16:12

connor.p


2 Answers

You can just remove the display: none; from myDiv. That way it will be visible from the beginning, and then you hide it after five seconds.

There is no need to first hide it with CSS, and then display it with JavaScript, when you want it to show up from the beginning.

<input type = "button" value = "Show image for 5 seconds" onclick = "show()"><br><br>
<div id = "myDiv"><img id = "myImage" src = "images/ajax-loader.gif"></div><br>

<script type = "text/javascript">   
setTimeout(function(){
   document.getElementById("myDiv").style.display="none";
}, 5000);  
</script>
like image 172
Christofer Eliasson Avatar answered Sep 28 '22 16:09

Christofer Eliasson


Just remove the onclick="show()", and add show(); as the last line of your JavaScript block.

Also, as I'm sensitive to global namespace pollution, I'd do it like this:

<script type="text/javascript">

  (function(){
    var myDiv = document.getElementById("myDiv"),

      show = function(){
        myDiv.style.display = "block";
        setTimeout(hide, 5000); // 5 seconds
      },

      hide = function(){
        myDiv.style.display = "none";
      };

    show();
  })();

</script>
like image 23
ziesemer Avatar answered Sep 28 '22 18:09

ziesemer