Loading or Refreshing a Div Content Using jQuery

To do this we will be using the normal setInterval in jQuery. We will create an element to be considered to be our container div. And by using setInterval, we will refresh the content that we created dynamically to our container div. I hope you will like this.

Please see this article in my blog

Using the code

To work with it, load your jQuery reference first. I am using the following version of jQuery.

  1. <script src="http://sibeeshpassion.com/content/scripts/jquery-2.0.2.min.js"></script>  

Create a container div

  1. <div id='container'></div>  

So now we can do our script part.

Implementation

Here's the scripts:

  1. $(document).ready(  
  2. function() {  
  3.    setInterval(function() {  
  4.       var randomnumber = Math.floor(Math.random() * 20);  
  5.       var html='';  
  6.       for(i=0;i<randomnumber;i++)  
  7.       {  
  8.          html+='<p>'+ randomnumber+ '</p>';  
  9.       }  
  10.       $('#container').html(html);  
  11.    }, 1000);  
  12. });  

As you can see, we are creating some random numbers less than 20.

  1. var randomnumber = Math.floor(Math.random() * 20);  

And assigning the random value to the dynamically created p tag.

  1. html+='<p>'+ randomnumber+ '</p>'  

Now we need to style our p tag as in the following:

  1. p {  
  2.    border: 1px solid #ccc;  
  3.    border-radius: 5px;  
  4.    height: 18px;  
  5.    width: 18px;  
  6.    padding: 5px;  
  7.    text-align: center;  
  8.    background-color: #999;  
  9.    color: #fff;  
  10.    float: left;  
  11. }  

That is all, it is time to run our code.

jsfiddle link: Loading or refreshing a div content jsfiddle

Output

Conclusion

I hope you liked this article. Please share with me your valuable feedback. Thanks in advance.