Random Picture Rotation with JavaScript
- Random Picture Rotation with JavaScript
- How the Rotating Images Code Works
- The Coding Plan
- Some Key JavaScript Concepts
- Detecting the Load Event
- Triggering the Function from the Load Event
- Generating Random Numbers
- Creating the Image Path
- DOM Scripting
- Assembling the Image Element
- Adding the Image Element to the Page
- Reviewing the Working Page
- Summary
Hopefully you (or your clients) have lots of regular site visitors, so you know it's a serious commitment to update the content constantly to keep the site looking fresh when visitors return. One of the most memorable parts of any web page is the images. In this article, I show you how to use JavaScript to randomly select and display one of a number of images when the page loads. Over multiple visits to your site, a visitor will see a variety of different images in a given page location (see Figure 1).
Figure 1 Each time the page is refreshed, a random image loads.
The reason I chose this example is that in its nine short lines it shows many interesting aspects of JavaScript. If you're a web designer but you haven't yet dug into this amazingly powerfuland empoweringlanguage, I'll show you some key concepts that will help you to understand JavaScript better, and perhaps give you a taste of JavaScript's capabilities to create whatever interface interactions your designs demand. If you have some experience with JavaScript, I hope this article will give you new insight and inspiration. In future articles, I'll continue to build on the ideas shown in this code.