Codesoft Codesoft - 5 months ago 10
jQuery Question

Jquery code to show loading before display the main content

I am working with

jquery
on my page, I want when ever user click on a button an image will show loading for 1 second before the main content appears

Here is my code:

<script>
$(document).ready(function(){
$("#UseractivityLog").click(function(){
$(".UserProfileLogs-cont").html("<img src='image/loading.gif'/>");
//Then for 1/2 seconds this UserProfileLogs will display
$(".UserProfileLogs").toggle();
});
$("#IdealLog").click(function(){
$(".UserProfileLogs-con").toggle();
});
});
</script>


Here is my HTML part

<a href="#" id="UseractivityLog">Logs</a>
<div id="UserProfileLogs-cont">
<div id="IdealLog"></div>
<div id="UserProfileLogs"></div>
</div>


Please i will appreciate jsfiled sample

Answer

You can use setTimeout to update the image source after n seconds.

Also you can achieve this using single div and an nested img without using separate container for loading icon and image.

Hope this below snippet will be useful

HTML

<a href="#" id="UseractivityLog">Logs</a>
<div id="UserProfileLogs-cont">
  <img src="">
</div>

JS

$(document).ready(function(){
var _gif = "http://assets.motherjones.com/interactives/projects/features/koch-network/shell19/img/loading.gif";
var _forest="http://www.discovertheforest.org/images/hero/home/6.jpg";
          $("#UseractivityLog").click(function(){
          $("#UserProfileLogs-cont img").attr("src",_gif);
          setTimeout(function(){
          $("#UserProfileLogs-cont img").attr("src",_forest);
          },3000)
        });  

      });

Check this jsfiddle

Comments