Ecommerce Developer
 
 

Code

Build a Simple Content Slider from Scratch

 

JavaScript libraries like jQuery, Prototype, YUI, and MooTools abstract many common JavaScript functions and eliminate most cross browser concerns. But for some projects these resources might be more than is required. Moreover, frequently using a library or library plugins can also make developers a little rusty where vanilla-flavored, standard JavaScript is concerned.

In this tutorial, I am going to help you clear away some of the rust, demonstrating how to create a basic content slider without the aid of a JavaScript library. Certainly, there is a lot of amazing content slider plugins already available that are free to use in your projects. But often these have more features than I really want or need and, therefore, add unnecessary file bloat.

What's more, content slider plugins typically manage some aspects of page or element style in the JavaScript, adding inline style elements where needed. But often I would rather handle the style with a CSS file, which is easier to do when you create your own slider.

Content Slider Components

My basic content slider is made up of three components, including a div element that serves as a container for the content that I will be manipulating; an unordered list; and a second div to encase the slider controls.

I give each of these important components an ID, so that I can easily add style descriptions and select the elements with JavaScript. Also, I am using images for my content slider, but each list item could contain just about anything from text to videos or a combination thereof.

	<div id="sled-wrap">
	<ul class="sled" id="sled">
	<li><img src="1.png" alt="1" /></li>
	<li><img src="2.png" alt="2" /></li>
	<li><img src="3.png" alt="3" /></li>
	<li><img src="4.png" alt="4" /></li>
	</ul>
	</div>
	<div id="sled-controls">
	<span id="prev">previous</span>
	<span id="next">next</span>
	</div>

Style Declarations

The first component to address is #slide-wrap. It will determine the content slider's visible dimensions and must have overflow set to hidden. This way I am only showing the user one list item at a time and obscuring the others.

#sled-wrap {width: 960px; height: 400px; border: #737373 solid 1px; overflow: hidden;}

Next, I add style declarations for the unordered list. It would display as a block, have no margins or padding, and must be wider than all of the list items combined. In the example, I arbitrarily set the width to 9,999 pixels.

#sled {display: block; list-style: none; width: 9999px; margin:0; padding:0; }

The list items should be exactly the same width and height as #sled-wrap . These items should also be floated left and positioned relatively.

#sled li {float: left; width: 960px; height: 400px; position: relative; 

At this point, loading the page in a browser should display the first list item, with the words, "previous" and "next" below it.

Image shows the first list item

Introduce the JavaScript

The JavaScript's purpose is to reposition the list items when a user clicks on one of the controls. To accomplish this feat we need first to know when a user clicks, so I begin by adding an event listener that will evoke a function called, initSled.

document.onclick = initSled;

Next, I know that I am going to get the unordered list, an array of list items, and the length of that array. I also suspect that I am going to need this information for more than one function, so I create these as global variables outside of any of the functions.

var sledUl = document.getElementById('sled');
var sledLi = sledUl.getElementsByTagName('li');
var sledLength = sledLi.length;

The initSled function will first compensate for browser differences and then take some action depending on where the user clicked on the page. I am using a switch, but I could have used a if, for example. You might even try a couple of different approaches to determine which performs best.

function initSled(e)
{

	
	if (!e) var e = window.event;
	var target = e.target || e.srcElement;

switch(target.id){
        case "prev":
            sledPrev();
            break;
        case "next":
            sledNext();			
            break;
}
	
}

The switch calls either sledPrev() or sledNext() depending on the ID of the element clicked. These two functions are very similar, so, perhaps we could eventually refine them into one, but for the time being they are separate.

Each function initiates a for loop. The loop first checks to learn if there is an inline style value set for "left." If that value does not exist, the JavaScript creates it with a value of -2880 pixels or -960 pixels depending on which element was clicked.

When the page loads, the "left" attribute's value is zero by default, thus slide or box one is displayed. When the "previous" or "next" button is clicked for the first time, the JavaScript must assign a new value, if that value is -960 the second slide or box is displayed, since the left positioning is offset by the exact width of the first list item. When "previous" is selected, I want the last slide or box to show. In this case, that slide is positioned at -2880 pixels.

Subsequent clicks add or subtract 960 pixels, and finally, if the slider reaches a limit on the left or right, it resets.

function sledPrev()
{
		
		for(var i =0; i < sledLength; i++)
		{
			if(!sledLi[i].style.left)
			{			
				sledLi[i].style.left = '-2880px';
			}
			else
			{
				var liPos = parseInt(sledLi[i].style.left);

				if(liPos < 0)
				{
					sledLi[i].style.left = (liPos + 960) + 'px';
					
				}
				else
				{
					sledLi[i].style.left = '-2880px';
				}
				
			}
			
		}
}
	

function sledNext()
{

		for(var i =0; i < sledLength; i++)
		{
			if(!sledLi[i].style.left)
			{			
				sledLi[i].style.left = '-960px';
			}
			else
			{
				var liPos = parseInt(sledLi[i].style.left);
				
				if(liPos > -2880)
				{
					sledLi[i].style.left = (liPos - 960) + 'px';
					
				}
				else
				{
					sledLi[i].style.left = '0';
				}
			
			}
			
		}
}

Shows a list item

We now have a functioning content slider. The transitions are instantaneous, but now that we've gotten rid of some of the rust, I leave it to you to decide how you want to manage the motion.

Related Articles

0 Comments

Rss-sm