Web Developer Tutorial: Build Your Own Image Scrollbar

By Curtis Dicken

Build Your Own Image Scrollbar By Curtis Dicken

Introduction to the Class

If you have been surfing the web for more than a day you've certainly come across an image scrollbar. In case you aren't sure exactly what I mean by that, it's a collection of thumbnail size images, usually in a table, with buttons on either side of the images that allow you to scroll through the collection. It's a great space saver when website real estate is hard to come by. In this article we'll walk through the JavaScript functions and HTML necessary to create an image scrollbar. The topics covered in this project will include Array, getElementById, setAttribute, setTimeout, onmouseover and onmouseout.

The Image Scroller Code

[Ed. note: you can view the script in action here.]
<html xmlns="http://www.w3.org/1999/xhtml" >

<head>

    <title>Scroll Bar Example</title>

</head>

<body>

    <script language="javascript" type="text/javascript">

    

    // Array of image paths

    var imagePath= new Array(10) 

    imagePath[0]="image1.png"; 

    imagePath[1]="image2.png"; 

    imagePath[2]="image3.png"; 

    imagePath[3]="image4.png"; 

    imagePath[4]="image5.png";

    imagePath[5]="image6.png"; 

    imagePath[6]="image7.png"; 

    imagePath[7]="image8.png"; 

    imagePath[8]="image9.png"; 

    imagePath[9]="image10.png";

    

    // Our index, boundry and scroll tracking variables

    var imageIndexFirst = 0;

    var imageIndexLast = 3;

    var continueScroll = 0;

    var maxIndex = 9;

    var minIndex = 0;

    

    // This function changes the images

    function changeImage(ImageToChange,MyImagePath){ 

        document.getElementById(ImageToChange).setAttribute('src',MyImagePath) 

        }

        

    // This function handles the scrolling in both directions

    function scrollImages(scrollDirection) {

        // We need a variable for holding our working index value

        var currentIndex;

        // Determine which direction to scroll - default is down (left)

        if (scrollDirection == 'up')

            {

                // Only do work if we are not to the last image

                if (imageIndexLast != maxIndex)

                    {

                        // We set the color to black for both before we begin

                        // If we reach the end during the process we'll change the "button" color to silver

                        document.getElementById('scrollPreviousCell').setAttribute('style','color: Black')

                        document.getElementById('scrollNextCell').setAttribute('style','color: Black')

                        // Move our tracking indexes up one

                        imageIndexLast = imageIndexLast + 1;

                        imageIndexFirst = imageIndexFirst + 1;

                        //  Change next "button" to silver if we are at the end

                        if (imageIndexLast == maxIndex)

                            {

                                document.getElementById('scrollNextCell').setAttribute('style','color: Silver')

                            }

                        // Change is scrollbar images in a set delay sequence to give a pseudo-animated effect

                        currentIndex = imageIndexLast;

                        changeImage('scrollThumb4',imagePath[currentIndex]);

                        currentIndex = imageIndexLast - 1;

                        setTimeout("changeImage('scrollThumb3',imagePath[" + currentIndex + "])",25);

                        currentIndex = imageIndexLast - 2;

                        setTimeout("changeImage('scrollThumb2',imagePath[" + currentIndex + "])",50);

                        currentIndex = imageIndexLast - 3;

                        setTimeout("changeImage('scrollThumb1',imagePath[" + currentIndex + "])",75);

                        // Wait and check to see if user is still hovering over button

                        // This pause gives the user a chance to move away from the button and stop scrolling

                        setTimeout("scrollAgain('" + scrollDirection + "')",1000);

                    }

                }

            else

                {

                    // Only do work if we are not to the first image

                    if (imageIndexFirst != minIndex)

                    {

                        // We set the color to black for both before we begin

                        // If we reach the end during the process we'll change the "button" color to silver

                        document.getElementById('scrollPreviousCell').setAttribute('style','color: Black')

                        document.getElementById('scrollNextCell').setAttribute('style','color: Black')

                        // Move our tracking indexes down one

                        imageIndexLast = imageIndexLast - 1;

                        imageIndexFirst = imageIndexFirst - 1;

                        //  Change previous "button" to silver if we are at the beginning

                        if (imageIndexFirst == minIndex)

                            {

                                document.getElementById('scrollPreviousCell').setAttribute('style','color: Silver')

                            }

                        // Change is scrollbar images in a set delay sequence to give a pseudo-animated effect

                        currentIndex = imageIndexFirst;

                        changeImage('scrollThumb1',imagePath[currentIndex]);

                        currentIndex = imageIndexFirst + 1;

                        setTimeout("changeImage('scrollThumb2',imagePath[" + currentIndex + "])",25);

                        currentIndex = imageIndexFirst + 2;

                        setTimeout("changeImage('scrollThumb3',imagePath[" + currentIndex + "])",50);

                        currentIndex = imageIndexFirst + 3;

                        setTimeout("changeImage('scrollThumb4',imagePath[" + currentIndex + "])",75);

                        // Wait and check to see if user is still hovering over button

                        // This pause gives the user a chance to move away from the button and stop scrolling

                        setTimeout("scrollAgain('" + scrollDirection + "')",1000);

                    }

                }

        }

        

    // This function determines whether or not to keep scrolling

    function scrollAgain(scrollDirection)

        {

            if (continueScroll == 1)

                    {

                        scrollImages(scrollDirection);

                    }

         }

         

    // This function kicks off scrolling down (left)

    function scrollPrevious() {

            continueScroll = 1;

            scrollImages('down');

        }

        

    // This function kicks off scrolling up (right)

    function scrollNext() {

            continueScroll = 1;

            scrollImages('up');

        }

        

    // This function stops the scrolling action

    function scrollStop() {

            continueScroll = 0;

        }

        

    </script>

    <table border="0" cellpadding="5" cellspacing="0" width="700px">

        <tr>

            <td align="center" colspan="6" style="background-color: maroon">

                <img height="400" src="image1.png" style="border-right: 1px solid; border-top: 1px solid; border-left: 1px solid;

                    border-bottom: 1px solid" width="400" /></td>

        </tr>

        <tr>

            <td id="scrollPreviousCell" style="color: Silver" onmouseover="scrollPrevious();" onmouseout="scrollStop();">

                &lt;&lt; Previous</td>

            <td>

                <img id="scrollThumb1" height="100" src="image1.png" style="border-right: 1px solid; border-top: 1px solid; border-left: 1px solid;

                    border-bottom: 1px solid" width="100" /></td>

            <td>

                <img id="scrollThumb2" height="100" src="image2.png" style="border-right: 1px solid; border-top: 1px solid; border-left: 1px solid;

                    border-bottom: 1px solid" width="100" /></td>

            <td>

                <img id="scrollThumb3" height="100" src="image3.png" style="border-right: 1px solid; border-top: 1px solid; border-left: 1px solid;

                    border-bottom: 1px solid" width="100" /></td>

            <td>

                <img id="scrollThumb4" height="100" src="image4.png" style="border-right: 1px solid; border-top: 1px solid; border-left: 1px solid;

                    border-bottom: 1px solid" width="100" /></td>

            <td id="scrollNextCell" style="color: Black" onmouseover="scrollNext();" onmouseout="scrollStop();">

                Next &gt;&gt;</td>

        </tr>

    </table>

 

</body>

</html>

The Variables

There are several variables that we need to create in order to track various aspects of our scrollbar. First and foremost we need an array of image paths which we enter into our imagePath array. The paths that you enter here will need to either be relative to the page where you place your scrollbar or be absolute paths. We'll also need variables to track where we are in the collection which we will use to determine whether to scroll or not and how to present our “buttons”. We also will need a variable that allows us to “switch” the scrolling on and off. Lastly, we'll add a couple of variables to define the upper and lower bounds of our image array.

Function - changeImage

This particular function is very straight forward. It receives the ID of the image element that needs changed and the new source(src) for that image. It then finds the HTML element by using getElementById and sets the source(src) attribute with setAttribute. Short, simple and sweet. This simple function has a myriad of uses beyond our scrollbar.

Function - scrollImages

This function is the workhorse of our project. It receives a single parameter that tells us which direction to scroll. Our next order of business is to check and see if we are at the beginning or end. If we can't move the up or down in the image collection we're all done and no other code gets executed. If we can move a direction we increment or decrement our index values (imageIndexFirst and imageIndexLast) that help us keep track of where we are in the collection. We also make sure that our previous and next “buttons” are the color black. If we need to gray one out because we have reached the beginning or the end we'll catch that in the next if statement.

Now for the fun part. We use our local currentIndex variable to get image path info out of our image array. We change the index in a specific order based on our scroll direction. If we are scrolling up (right) we change our images from right to left by incrementing the index. Moving our scrollbar down (left) we change our images from left to right. We also use setTimeout when we call our changeImage function. This causes a specific delay before the function is called. We stagger the delays by a quarter of a second (25 milliseconds) so that we can create a pseudo animation effect.

The last thing we need to do is determine whether or not to continue scrolling. Before we do that, however, we want to give the user time to move the pointer off of the “button” so we use setTimeout to delay calling the scrollAgain function which determines whether to continue scrolling.

Function - scrollAgain

This simple function takes a look at our continueScroll variable that we use to determine whether we should continue scrolling. If the value of continueScroll is 1 then we keep going by calling the scrollImages function again, otherwise we do nothing and scrolling stops.

Function - scrollPrevious

This function kicks off the scrolling process by setting the continueScroll variable to 1 and calling the scrollImages function with parameter value of “down”.

Function - scrollNext

This function also kicks off the scrolling process by setting the continueScroll variable to 1 and calling the scrollImages function with parameter value of “up”.

Function - scrollStop

This function sets the value of the continueScroll variable to 0 which will stop the scrolling process the next time the scrollAgain function is executed.

The HTML

For the most part the HTML in our project is just a collection of image elements in a table. What you will need to note is the fact that each of our thumbnail images has a specific ID assigned to it so that our changeImage function can find them. The cells for our previous and next “buttons” also have specific ID values assigned so that we can change the style attribute to gray out buttons when required. The cells also include the onmouseover event which calls our scrollPrevious and scrollNext functions. This starts the scrolling process. The other event we use is the onmouseout which calls our scrollStop function so that we can stop the scrolling process when the user moves their pointer off of the “button”.

Conclusion

This is a very simple to implement bit of JavaScript that creates an easily managed effect. It's a great space saver when you need to get a lot of images on a page but just don't have the space. Try customizing it by changing the number of thumbnails, playing with the setTimeout delay values, or changing the number of image paths in the array. You can also use the onmouseover and onmouseout events with other elements like span and img if you don't like my basic “buttons”.

Now, before you start sending your emails telling me how I can consolidate my code, keep in mind I intentionally was more verbose than necessary for the beginners. Happy coding!

Make a Comment

Loading Comments...

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
  •  
  •  
  •  
Thanks for your registration, follow us on our social networks to keep up-to-date