How to Get Rotating Images on My Web Page and Place Them Anywhere on the Page

By Darrin Koltow

Updated April 05, 2018

Images that change automatically are inherently interesting to watch, which makes them ideal for keeping viewers on your website. Image cycling requires just a few lines of JavaScript. One approach relies on the setInterval statement, which runs any function you choose at periodic intervals. To easily position your images in the desired location on your Web page, specify the location's coordinates with the Top and Left properties of CSS.

Open Notepad, and then paste the following HTML statements into the document. These statements define a basic, blank Web page, into which you can insert statements for displaying cyclical images:

Paste the following statements after the <BODY> HTML tag. This tag defines a placeholder for an image file called "b1.jpg." Even though this statement is hard-coded, JavaScript and CSS statements can change the placeholder's position and content:

Paste the following JavaScript statements just above the <img> tag. The statements prior to the changeImage function create image variables for that function, and then use setInterval to call that function at periodic intervals. The changeImage function uses the document.getElementById statement to insert images from the myImages array into the <img> tag:

Paste the following CSS statements immediately under the <HEAD> tag. These statements indicate the location of the page's <img> tag, in units of pixels. This location can be anywhere you specify. Type over the 230 and 200 values shown here with different values -- roughly from zero to 800 for the Top property, and zero to 1000 for the Left property. The display resolution of the PC or other device that shows your Web page sets the actual range, and therefore will vary. However, all devices will display the images in the upper left corner if you type "0" for both the Top and Left properties:

Save the file with the ".htm" file extension, and then copy four images numbered consecutively from "b1.jpg" through "b4.jpg" into the same folder.

Open the Web page in your Web browser to view the continuously changing images.


Information in this article applies to HTML 5. It may vary slightly or significantly with other versions.