jQuery DIV Auto Load and Refresh

jQuery load method requests server pages and refreshes HTML selector with the page content. In this tutorial, we are going to auto load and refresh a DIV with a periodic interval.

This jQuery auto load tutorial will help to refresh content with very latest feeds, to load random advertisement banners and etc.

jquery-div-auto-load-refresh

View Demo

jQuery Auto Load

Very few lines of code are required for the jQuery auto load. And it is,

<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
setInterval(function(){
$("#screen").load('banners.php')
}, 2000);
});
</script>

The PHP file banners.php is requested via jQuery ajax using load method. This file contains an array of HTML color codes. One of those colors is picked using PHP array rand to change banner backgrounds and loaded into a specified DIV. The PHP code is,

<?php
$bg_array = array("#CEED9D","#ECED9D","#EDCF9D","#EC9CA7","#ED9DD0","#EE9DE2","#D69DEC","#9E9CEC");
$bg = array_rand($bg_array,1);
?>
<div class="banner" style="background-color:<?php echo $bg_array[$bg];?>;" >
<div class="txt-title">jQuery DIV Auto Load Refresh</div>
<div class="txt-subtitle">This Banner auto loads and refreshes every 2 seconds.</div>
</div>

This jQuery load event happens every 2 seconds to update the banner periodically. Instead of using static array data we can connect DB to load div with dynamic data.

View DemoDownload

This jQuery code tutorial was published on October 5, 2014.

↑ Back to Top