JavaScript Slideshows Made Easy
People use everything from Adobe Flash to jQuery to add interactive slideshows to their sites. Learn to change an HTML image’s src property, and you are minutes away from creating your own slideshow using nothing but JavaScript. As you’ll discover, adding an entertaining or informative image slideshow to your blog or site is an excellent way to learn many JavaScript fundamentals that can help you develop more complex Web projects in the future.
New to JavaScript? Learn it quickly at Udemy.
JavaScript Slideshow Ingredients
HTML tags have attributes whose properties you can change. The img tag’s src attribute is one of the most important ones because it contains the URL of the image the tag makes appear in your browser. This URL can be an absolute URL, such ashttp://www.whitehouse.gov/building.jpg, or a relative URL that points to an image in a directory on your website. A relative URL, such as the one shown below, often consists of an image’s name.
<img src=”mountains.jpg” alt=”mountains”>
You’ll probably set the src attribute’s value when you write your page’s HTML code. Because JavaScript can change an attribute’s value dynamically, you can write a simple function that replaces an image with new images when people click “Next” and “Previous” buttons on your slideshow page.
Although it only takes a single statement to alter an img tag’s src attribute, you’ll need additional methods and objects to build a basic slideshow. Here are some of the thing’s you’ll learn doing that:
- DOM Querying – The Document Object Model, or DOM, is one of the most important entities to understand if you wish to create advanced JavaScript applications. Before you can change an img tag or any other DOM element, you must find it by querying the DOM.
- Arrays – An array is a collection of items. You’ll use an array to hold the names of your slideshow images.
- Event Handlers – Web page elements can respond to clicks and other actions site visitors perform. If you add click events to “Previous” and “Next” buttons, site visitors can click them to navigate through your slideshow.
Pick up valuable tips about arrays and the DOM at Udemy.
Initialize Important Variables
Add the following code to your HTML document’s script section:
var images = ["Image1.jpg", "Image2.jpg", "Image3.gif"];
This statement creates an array that contains the names of three images. Replace those names with the URLs of three images that reside on the Web or the full path names of three images that lie in a folder on your Web server. Quotes surround each element in the array because this array contains string elements.
Paste the following statement below the array declaration:
var arrayIndex = 0; window.onload = init;
This variable named arrayIndex will help you navigate through the images array and display different images. JavaScript arrays use a zero-based indexing system. This means that an array’s first element is 0, the next element is 1, the next element is 2, etc. That’s why the arrayIndex’s initial value is 0; it points to the first image in the images array.
Place the code shown below after the first two statements described above:
var myImage;
You’ll use the myImage variable later to hold a reference to your HTML document’s img tag. The final statement creates an onload event that tells JavaScript to run a function named init after a Web page loads.
Create User Interface
You only need one img tag to make a slideshow appear on a Web page. Add the following code to a new HTML document:
<img id="mainImage" src=Image1.jpg"> <button id="buttonPrevious">Previous Slide</button> <button id="buttonNext">Next Slide</button>
The img tag has an ID named “mainImage” that will help your JavaScript find that element later. Change the src URL from “Image1.jpg” to the image array’s first element.
The next two lines of code create two buttons. They also have unique IDs JavaScript can use to find those buttons as needed. Save the document if you like and view it in a browser. You’ll see an image sitting above a “Previous Slide” button and a “Next Slide” button.
Set Up Event Handlers
Sometimes you need an initialization function when you wish to access page elements before browser finishing loading a Web page. If you create a window.onload event that runs a function such as init on page load, you can access any page element before it loads. Add the following init function to your document’s script section:
function init() { myImage = document.getElementById("mainImage"); var buttonPrevious = document.getElementById("buttonPrevious"); var buttonNext = document.getElementById("buttonNext"); if (buttonPrevious.addEventListener) { buttonPrevious.addEventListener("click", function () { processClicks("previous") }, false); buttonNext.addEventListener("click", function () { processClicks("next") }, false); } else if (buttonPrevious.attachEvent) { buttonPrevious.attachEvent("onclick", function () { processClicks("back") }); buttonNext.attachEvent("onclick", function () { processClicks("next") }); } }
The first statement obtains a reference to your img element and stores it in the myImage variable. The next two statements get references to the two buttons you added. Study the code block that begins with this statement:
if (buttonPrevious.addEventListener) {
It checks to see if the button who’s ID is buttonPrevious supports the addEventListener method. AddEventListener enables you to add an event to an element. In this instance, JavaScript executes the code in the “if” block if this button supports the addEventlistener method. That code in the “if” block adds a click event to the button. When someone clicks that button, the event handler calls the processClicks function and passes it the word “previous.” You’ll use processClicks to manage the slideshow images.
Note the following statement that sits now far below the statement that adds a click event to the button who’s ID is buttonPrevoius:
buttonNext.addEventListener("click", function () {
This code adds a similar event listener to the button whose ID is “buttonNext.”
Finally, notice the code that begins with the following statement:
else if (buttonPrevious.attachEvent) {
If a site visitor’s browser does not support the addEventListener method, JavaScript checks to see if the browser supports the attachEvent method. It does the same job as the addEventlistener. The reason you must perform this type of checking is because versions of Internet Explorer 9 earlier than IE9 only support attachEvent. Master event handlers by visiting Udemy.
Create Image Swapping Function
The only thing you need now is the processClicks function that the button click event handlers call. Paste this function into your document’s script section:
function processClicks(action) { if (action == "previous") arrayIndex-=1; else if (action == "next") arrayIndex++; if (arrayIndex < 0 || arrayIndex > images.length-1) arrayIndex = 0; myImage.src = images[arrayIndex]; }
As you can see, it’s simple compared to the init function. The processClicks function accepts an argument from the buttons that people click. It them increments or decrements your arrayIndex variable depending on whether someone clicked “Next Slide” or “Previous Slide.” The line of code that make your images change is shown below:
myImage.src = images[arrayIndex];
It simply sets your img’s src attribute value to the appropriate element in your images array. When arrayIndex’s value exceeds the array length or falls below 0, the code sets the value to 0 — the first image in your array.
Save your document, open it in a browser and click the buttons to navigate through your new slideshow. You don’t have to use buttons to make the slideshow’s images change; your code can call processClicks(action) any time. Replace action with “previous” to move to the previous slide or “next” to move to the next one. Feel free to add or remove as many names as you like to your images array. It’s the only thing you need to update whenever you want to change your slideshow.
Recommended Articles
Top courses in JavaScript
JavaScript students also learn
Empower your team. Lead the industry.
Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.