Changing Previous Next Background-image Using Javascript

Updated on 23 Mar 2012,
Published on 26 Nov 2009

The JavaScript client side scripting language provides the functionality to change the Background-image of the targeted HTML element dynamically on click event of previous next hyperlinks by using the backgroundImage property of style object. In the previous tutorial: JavaScript Change Div Background-Image onclick we learnt how to set the background image of HTML div element dynamically on client side click event of button control. But here in this tutorial we will modify and extend that functionality. In this tutorial we will use HTML anchor <a> tag i.e. hyperlink element. The logic to toggle two images on the click event of button control is entirely different from the logic for changing multiple images on click event of HTML hyperlink elements.

JavaScript DOM Examples:

You can see the live samples and examples of JavaScript DOM from the following links:

For creating the functionality to change the images on click of previous next links first of all we need a javascript Array collection to store the multiple images. Next we require individual functions that will execute on click event of previous and next hyperlinks. The logic placed inside these functions will provide the functionality to change the multiple images in next and previous order.

Sample JavaScript Code for Changing Background-images

External CSS Code
#div1 {
    height: 38px;
    width: 120px;
    background-image: url(images/image1.jpg);
    background-repeat: no-repeat;
}
HTML Code + JavaScript Code
<html>
<head>
    <title>JavaScript Sample</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
    <script language="javascript" type="text/javascript">
    <![CDATA[
        // create an array to store the names of images
        var myArr = new Array();
        myArr[0] = 'images/image1.jpg';
        myArr[1] = 'images/image2.jpg';
        myArr[2] = 'images/image3.jpg';
        myArr[3] = 'images/image4.jpg';
        myArr[4] = 'images/image5.jpg';

        // A global variable
        var hiddenArrayIndex;

        // this function will change the image to the previous image
        // stored in the array
        function movePrevious() {

            // get the value stored in the hidden field
            hiddenArrayIndex = document.getElementById('hiddenValue').value;

            // if the value is not 0 then decrement the value by 1 and 
            // store it back into the hidden field.
            if (hiddenArrayIndex != 0) {
                document.getElementById('hiddenValue').value = 
                                    parseInt(hiddenArrayIndex) - 1;

                // re-assign the value to the hiddenArrayIndex variable
                hiddenArrayIndex = document.getElementById('hiddenValue').value;
            }

            // set the background-image stored at the specified Array Index dynamically
            document.getElementById("div1").style.backgroundImage = 
                                    "url(" + myArr[hiddenArrayIndex] + ")";
        }

        // this function will change the image to the next image
        // stored in the array
        function moveNext() {

            // get the value stored in the hidden field
            hiddenArrayIndex = document.getElementById('hiddenValue').value;

            // if the value is not equal to the upper index of the array
            // then increment the value by 1 and store it back into the hidden field
            if (hiddenArrayIndex != (myArr.length - 1)) {
                document.getElementById('hiddenValue').value = 
                                    parseInt(hiddenArrayIndex) + 1;

                // re-assign the value to the hiddenArrayIndex variable
                hiddenArrayIndex = document.getElementById('hiddenValue').value;
            }

            // set the background-image stored at the specified Array Index dynamically
            document.getElementById("div1").style.backgroundImage = 
                                    "url(" + myArr[hiddenArrayIndex] + ")";
        }
    ]]>
    </script>
</head>
<body>
    <center>
        <div id="div1">
        </div>
        <br />
        <a id="prev" href="#" onclick="movePrevious();">prev</a> 
        <a id="next" href="#" onclick="moveNext();">next</a>
    </center>
    <input type="hidden" id="hiddenValue" value="0" />
</body>
</html>

In the above code we have attached the external CSS code file saved with name style.css. You can add the above discussed CSS styles in the style.css file. The body section of HTML page contains the div tag, anchor tags and a hidden field control. The hyperlink tags will raise the client side click events which will change the background of image div tag. We have used the hidden field control to save the selected array index that enables you to display the image stored at that particular index. You can understand the flow and step by step logical functionality from the comments added inside the javascript code and also try its online sample output by following the link below.

Output:

You can see the output of above discussed codes from the following link:

Change Previous Next Background image

Continue to next tutorial: Expand Collapse Sidebar Navigation using JavaScript dynamically to learn show or hide the sidebar.

4 Responses to "Changing Previous Next Background-image Using Javascript"
Adisa
Hi, I used your scrip and it works great! Just one problem. When changing prev/next background image there is a flickering problem. Is there something to do about that? Thank you in advance! Adisa
Ezineasp.net
Hi Adisa

Flickering problem of images is a common problem that occurs due to image caching by browser. This problem occurs before first time loading of images and after that it works fine.

If its not the case then you can try optimising the images to reduce their size so that web browsers could cache and load the images quickly.
Luke
I wonder if you can add a fade effect with jquery?
Ezineasp.net
Hi Luke

Fade effect can be added simply by adding fadeTo() function of JQuery. You can download the latest version of jquery script and include it on your page by adding a script tag in the head section as following:

<script src="jquery-1.4.3.js" type="text/javascript"></script>

next create a fadeEffect() function to apply the jquery fade effect as following:

function fadeEffect() {
$("#div1").fadeTo("fast", 0.2);
$("#div1").fadeTo("slow", 1);
}

You can call this function inside the movePrevious and moveNext functions at the end. It will load the images with fade out and fade in effects.

Cheers! :)
Leave a Comment
* required
* required
* will not be published
* optional
* hint: http://www.example.com
  • Subscribe via Email
  • HIRE EzineASP.Net Developers