Implementing Background Image Change on Refresh Using Javascript
💻 coding

Implementing Background Image Change on Refresh Using Javascript

1 min read 147 words
1 min read
ShareWhatsAppPost on X
  • 1The article explains how to change the background image on page refresh using a simple JavaScript function.
  • 2It requires only five lines of code to implement the background change effect in a web project.
  • 3The tutorial includes a folder with background image files and demonstrates the use of Math.random() for random selection.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The article explains how to change the background image on page refresh using a simple JavaScript function."

Implementing Background Image Change on Refresh Using Javascript

Aol.com home page is changing the background image on every refresh, quite interesting. So how to apply this kind of effect to your web project, take a quick look this post. It’s simple just five lines of javascript code. Use it and enrich your web project user interface.

The tutorial contains a folder called bgimages with background images files.

index.html

bgimages

-- 1.jpg

-- 2.jpg

-- 3.jpg

-- ....

-- ....

Javascript

Here variable totalCount is the number of backgrounds. The Math.random() method returns a random number between 0 and 1 and the Math.ceil() method rounds a number towards to the nearest integer, and returns the result.

<html>
<head>
<script type="text/javascript"> 
var totalCount = 8;
function ChangeIt() 
{
var num = Math.ceil( Math.random() * totalCount );
document.body.background = 'bgimages/'+num+'.jpg';
document.body.style.backgroundRepeat = "repeat";// Background repeat
}
</script>
</head>
<body> 
// Page Design 
</body> 
<script type="text/javascript"> 
ChangeIt();
</script> 
</html>

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 22 August 2019 · 1 min read · 147 words

Part of AskGif Blog · coding

You might also like

Implementing Background Image Change on Refresh Using Javascript | AskGif Blog