jQuery DIV Auto Load and Refresh

by Vincy. Last modified on July 13th, 2022.

jQuery load method requests server pages and refreshes the 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 the very latest feeds, load random advertisement banners and etc.

View Demo

jQuery Auto Load

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

$(document).ready(function() {
	setInterval(function() {
		$("#screen").load('banners.php')
	}, 2000);
});

The PHP file banners.php is requested via jQuery ajax using load method.

jquery-div-auto-load-refresh

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

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

↑ Back to Top

Share this page