Wednesday, July 14, 2010

Simple Image Slider
















Recently, I have created image slider for a website like one displayed above. User can navigate to particular image by clicking on an image number otherwise Images to rotate one after other. When a user hovers a mouse over a number, image rotation stops. On mouse out rotation resumed.


Here are the code and description of my approach to implement this type of slider.

First of all, the image name should be same except last few digits like as displayed below.

e.g shoes_image1.jpg, shoes_image2.jpg, shoes_image1.jpg

So that you can synchronize image rotation through a loop using some variable. To begin slider a JavaScript function called from body onLoad method.


<body onload="slideImage();" onunload="clearTimer();">

Here slideImage function initiates sliding.

Here is the complete JavaScript code.

var _currentImage=0;
var _currentBrand
var _interval;
function changeImage(_imgNumber)
{
for(var i=1;i<=5;i++)

{
document.getElementById('imgCell'+i).style.border='1px solid black';
}
document.getElementById('images').style.background='url(plastic_parts_'+_imgNumber+'.jpg) no-repeat';
document.getElementById('imgCell'+_imgNumber).style.border='';
}

function slideImage()
{
_currentImage++;
if(_currentImage>4)
{
_currentImage=1;
}
document.getElementById('images').style.background='url(plastic_parts_'+_currentImage+'.jpg) no-repeat';
_interval=setTimeout("slideImage()",3000);
}

function clearTimer()
{
clearTimeout(_interval);
}

function resetTimer()
{
_interval=setTimeout("slideImage()",3000);
}

and here is HTML code.

<div id="images" style="border-width: 1px; border-style: solid; border-color: black; width:500px; height:500px; overflow:hidden; background: url(plastic_parts_1.jpg) no-repeat;">
<table style="position:relative; top:460px; left:10px; background-color:#EAEAEA;">
<tr>
<td id="imgCell1" style="border: 1px solid black; width:20px;"><center><a style="color:black;" href="javascript:" onclick="changeImage(1);" onMouseOver="clearTimer();" onMouseOut="resetTimer();">1</a></center></td>
<td id="imgCell2" style="border: 1px solid black; width:20px;"><center><a style="color:black;" href="javascript:" onclick="changeImage(2);" onMouseOver="clearTimer();" onMouseOut="resetTimer();">2</a></center></td>
<td id="imgCell3" style="border: 1px solid black; width:20px;"><center><a style="color:black;" href="javascript:" onclick="changeImage(3);" onMouseOver="clearTimer();" onMouseOut="resetTimer();">3</a></center></td>
<td id="imgCell4" style="border: 1px solid black; width:20px;"><center><a style="color:black;" href="javascript:" onclick="changeImage(4);" onMouseOver="clearTimer();" onMouseOut="resetTimer();">4</a></center></td>
</tr>
</table>
</div>


Hope this helps. Let me know if you have any questions.


No comments:

Post a Comment