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.
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With