Simple Image Slideshow

Discussion in 'JavaScript' started by samo1215, Jun 30, 2009.

  1. #1
    I am trying to create a simple image slide show in javascript with the aid of jquery. I have been reading tutorials and looking at code and while I understand the basics of javascript and how jquery works I have no idea how to actually put them to use to create this simple task.

    All I want to do is take an unordered list of 5 images and cycle through them, preferably by fading one image into the next. I don't need any fancy options or features and the images will already be properly sized. Any guidance on how to get started would be greatly appreciated.

    I should mention that I don't want to use a plugin or copy somebody's code, I want to understand how to do this myself.
     
    samo1215, Jun 30, 2009 IP
  2. JavaScriptBank.com

    JavaScriptBank.com Peon

    Messages:
    141
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #2
    JavaScriptBank.com, Jun 30, 2009 IP
  3. Mike H.

    Mike H. Peon

    Messages:
    219
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    0
    #3
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <title>None</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript">	
    
    /*  -------------------------------- Copyright Notice and User License -------------------------------------  */
    /*													      */
    /* 		Thumbnail Slideshow   Copyright 2009, MJH  wwww.javascript-demos.com  All rights reserved.    */
    /* 	You may use and distribute this document subject to the conditions contained in this notice.	      */
    /* 	The JavaScript code and HTML in this document are my copyrighted intellectual property. 	      */
    /* 	No part of this document may be changed without my written consent, except that styles and/or 	      */
    /* 	the values of the JavaScript configuration variables may be changed at will, and meta description     */	
    /*      and keyword tags may also be deleted or changed, at will.					      */	
    /*					      								      */
    /* 	This entire notice must be kept intact, in a Head section of the document where the code is used      */
    /*	and may NOT BE MOVED to an external file. 							      */
    /*													      */
    /*	This notice is your license to use and distribute this ENTIRE document for free, subject to the       */
    /*	above conditions.     										      */
    /*	You may NOT otherwise copy or transfer any part, or parts of this document. 			      */
    /*	You may NOT sell, copy or otherwise transfer this document, nor any part hereof, for any valuable     */
    /*	consideration.      				      						      */
    /*	You may NOT include this document nor any part hereof, in any compilation or other collection         */
    /*	which is  offered to others in any form, upon any medium, whether or not for valuable consideration.  */
    /*	 	      			      								      */
    /*  -------------------------------- Copyright Notice and User License -------------------------------------  */
    
    	var imgPath = "";    // set path to an empty string if using puplic URLs,
    			     // otherwise use the path to your image folder, e.g. "./images/"
    
    	var slideInterval = 3;  // a new image every 3 seconds;
    	var imgSet = [];
    
    /* Image and caption set for the first slideshow; */
    	imgSet[1]  = ["http://lh5.ggpht.com/_kyE7dUMGYI0/SimqIDKjI8I/AAAAAAAACPk/f5rtq20HkuE/s576/_DSC9736.jpg | This is a caption",
    		     "http://lh3.ggpht.com/_-9n_sfftzqc/SituGRaSoWI/AAAAAAAAAqs/ZBow2YUH1o4/s640/DSC_1263.jpg | Another caption",
    		     "http://lh3.ggpht.com/_t6JTBTiIM30/SibzvCR8m0I/AAAAAAAABfs/SUQxUJ2YG68/s512/Picture%20254.jpg | This image has a caption", 
    		     "http://lh4.ggpht.com/_HJpL4RKzAUQ/Si76BuUfdHI/AAAAAAAAB0g/9yAVkOeiHnk/s576/IMG_1184.JPG | A caption for this image",
    		     "http://lh3.ggpht.com/_Y4aOa8bggGg/Sjqp0Om8PwI/AAAAAAAACY4/iF86mdsA-jA/s576/Elephant%20de%20mer%20-%20Pointe%20Morne%20-%20Kerguelen.jpg | Just another caption"];
    
    /*      You may have as many image sets as you need.  */
    /*
    	imgSet[2]  = ["tower_city.jpg | Tower City Fountain", "society_tower.jpg | Society Bank Tower", "skyline.jpg | Cleveland Skyline", 
    		      "rock_hall.jpg | Rock & Roll Hall of Fame", "free_stamp.jpg | Free Stamp", "playhouse.jpg | Playhouse Square",
    		      "ballpark.jpg | Cleveland Indians Ballpark", "hard_rock.jpg | Hard Rock Cafe Guitar"];
    	
    */
    	var imgIndex = [];
    	var playIndex = [];
    	var groupIndex = [];	
    	var intervalIndex = [];	
    	var startImg = "";
    	var nSection = "";
    	var sWidth = screen.width;
    	var sHeight = screen.height;	
    	var nV = 0;	
    
    	function displayFull(){
    
    		var nContainer = document.getElementById('popImgContainer');
    		nContainer.style.left = Math.round((sWidth - document.getElementById('nullImg').width)/2) + "px";	
    		nContainer.style.top = Math.round(((sHeight - document.getElementById('nullImg').height)/4) - 30) + nV + "px";						
    	}
    
    	function openFullSize(nSrc,nCap){
    		
    		document.getElementById('nullImg').src = nSrc;
    		document.getElementById('popImgCaption').innerHTML = document.getElementById(nCap).innerHTML;
    		setTimeout("displayFull()",1000);  // you may need to "adjust" the 1000;		
    	}
    
    	function stayHome(){
    
    		nV = document.documentElement.scrollTop;
    		setTimeout("stayHome()", 150);
    	}
    
    	function autoTurn(nSet,nIdx,stopShow){
    
    		for (i=0; i<playIndex.length; i++)
    			{
    			 if (playIndex[i] == 1 &&  i != nIdx)
    				{
    				 return;
    				}
    			}	
    		if (stopShow)
    			{
    			 startImg = "";
    			}
    		nSet.value == "Start" ? nSet.value = "Stop" : nSet.value = "Start";
    		nSet.alt == "Start Slideshow" ? nSet.alt = "Stop Slideshow" : nSet.alt = "Start Slideshow";
    		nSet.title == "Start Slideshow" ? nSet.title = "Stop Slideshow" : nSet.title = "Start Slideshow";
    		playIndex[nIdx] == 0 ? playIndex[nIdx] = 1 : playIndex[nIdx] = 0;		
    		for (i=1; i<playIndex.length; i++)
    			{
    			 if (playIndex[i] == 1)
    				{				 				 
    				 turnPage('next',groupIndex[i]);
    				 intervalIndex[i] = setInterval("turnPage('next',"+groupIndex[i]+")", slideInterval * 1000);				 
    				}
    			 if (playIndex[i] == 0)
    				{
    				 clearInterval(intervalIndex[i]);	
    				 intervalIndex[i] = "";					
    				}				 	 
    			}		
    	}
    	
    	function turnPage(direction,nIdx,nBtn){			
    		
    		if (startImg != "" && nBtn)
    			{
    			 return;
    			}	
    		if (document.forms[nIdx-1]['slideShowBtn'].value == "Stop" && startImg == "")
    			{
    			 startImg = imgSet[nIdx][imgIndex[nIdx]];				 
    			}		
    		var nPages = imgSet[nIdx].length - 1;	
    		if (direction == 'next')
    			{
    			 if (imgIndex[nIdx] < nPages)
    				{
    				 imgIndex[nIdx]++;				 
    				} 
    			 else	{
    				 imgIndex[nIdx] = 0;
    				}			 
    			}	
    		if (direction == 'prev')
    			{
    			 if (imgIndex[nIdx] > 0)
    				{
    				 imgIndex[nIdx]--;	
    				} 
    			 else	{
    				 imgIndex[nIdx] = nPages;
    				}			
    			}
    		if (direction == 'first')
    			{
    			 imgIndex[nIdx] = 0;
    			}
    		if (direction == 'last')
    			{
    			 imgIndex[nIdx] = nPages;
    			}		
    		document.getElementById('pagingImg'+nIdx).src = imgPath + imgSet[nIdx][imgIndex[nIdx]].replace(/\|.+$/,"");
    		document.getElementById('caption'+nIdx).innerHTML = imgSet[nIdx][imgIndex[nIdx]].replace(/^.+\|/,"");
    		if (startImg == imgSet[nIdx][imgIndex[nIdx]])
    			{
    			 startImg = "";
    			 autoTurn(document.forms[nIdx-1]['slideShowBtn'],nIdx);
    			}
    	}
    
    	function shuffle(nSet){
    
    		for (r=0; r<nSet.length; r++)
    			{
    			 var tmp1 = parseInt(Math.random()*nSet.length);
    			 var tmp2 = parseInt(Math.random()*nSet.length);
    			 var tmp3 = nSet[tmp1];
    			 nSet[tmp1] = nSet[tmp2];
    			 nSet[tmp2] = tmp3;
    			}		
    	}
    
    	function init(){
    		
    		for (i=1; i<imgSet.length; i++)
    			{
    			 shuffle(imgSet[i]); // comment or delete this line if you do not want the images randomized;
    			 imgIndex[i] = 0;
    			 playIndex[i] = 0;
    			 groupIndex[i] = i;
    			 intervalIndex[i] = "";
    			 document.getElementById('pagingImg'+i).src = imgPath + imgSet[i][0].replace(/\|.+$/,"");
    			 document.getElementById('caption'+i).innerHTML = imgSet[i][0].replace(/^.+\|/,"");
    			 document.getElementById('pagingImg'+i).alt = "Click to Enlarge";
    			 document.getElementById('pagingImg'+i).title = "Click to Enlarge";
    			 document.getElementById('pagingImg'+i).onclick = function()
    				{
    				 nSection = this.id.replace("pagingImg","");				
    				 if (document.forms[nSection-1]['slideShowBtn'].value == "Stop")
    					{
    					 autoTurn(document.forms[nSection-1]['slideShowBtn'],nSection);
    					}
    				 openFullSize(this.src,this.id.replace("pagingImg","caption"));
    				}
    			 }
    			 var nBody = document.getElementsByTagName("body")[0];
    			 var nDiv = document.createElement("div");
    			 var nImg = document.createElement("img");
    			 var nCaption = document.createElement('div');
    			 nDiv.id = "popImgContainer";
    			 nImg.id = "nullImg";
    			 nImg.alt = "Click to close";
    			 nImg.title = "Click to close";
    			 nCaption.id = "popImgCaption";
    			 nDiv.appendChild(nImg);
    			 nDiv.appendChild(nCaption);
    			 nBody.appendChild(nDiv);
    			 nDiv.style.cursor = "pointer";
    			 nDiv.style.position = "absolute";
    			 nDiv.style.top = "-2000px";
    			 nDiv.style.border = "1px solid black";
    			 nDiv.onclick = function()
    				{
    			 	 this.style.top = "-2000px";
    				 if (startImg != "")
    					{
    				 	 setTimeout("autoTurn(document.forms[nSection-1]['slideShowBtn'],nSection)", 1000);
    					}
    				}
    			 nCaption.className = "popImgCaption";	
    			 stayHome();					
    	}
    
    	navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false);	
    
    </script>
    <style type="text/css">
    
    	 body {background-color: #f5f5f5; margin-top: 50px;}
    	 form {width: 245px; margin-right: auto; margin-left: auto; margin-top: 8px; padding-left: 16px;}
    	.pagingBtn {background-color: #87ceeb; font-size: 10pt; font-family: arial; font-weight: bold; 
    		    padding-left: 3px; padding-right: 3px; border: 1px solid black; margin-right: 15px;}
    	.imgContainer {width: 325px; margin-top: 25px; margin-left: auto; margin-right: auto; }
    	.imgContainer img {width: 325px; height: 240px; cursor: pointer; border: 1px solid blue; 
    			   position: relative; top: 4px;}
    	.captions {background-color: #f0e68c; color: #000000; width: 328px; text-align: center; font-size: 10pt;
    		   font-family: tahoma; font-weight: bold; margin-left: auto; margin-top: 1px;
    		   margin-right: auto; padding-top: 4px; padding-bottom: 3px;}	
    	.popImgCaption {font-family: tahoma; font-size: 14pt; text-align: center; color: #4169e1; 
    			background-color: #ffffe0; padding-top: 1px; padding-bottom: 1px;}
    	
    	
    </style>
    </head>
    	<body>
    		<div class="imgContainer">
    			<img src="null" id="pagingImg1">
    		</div>
    
    		<div id="caption1" class="captions"></div>
    
    		<form action="">						
    					                                  			<!-- direction, image set number -->
    			<input type="button" value="<<" class="pagingBtn" alt="First" title="First" onclick="turnPage('first',1,this)">
    			<input type="button" value="<" class="pagingBtn" alt="Previous" title="Previous" onclick="turnPage('prev',1,this)">
    			<input type="button" name="slideShowBtn" value="Start" class="pagingBtn" alt="Start Slideshow" title="Start Slideshow" onclick="autoTurn(this,1,true)">
    			<input type="button" value=">" class="pagingBtn" alt="Next" title="Next" onclick="turnPage('next',1,this)">
    			<input type="button" value=">>" class="pagingBtn" alt="Last" title="Last" onclick="turnPage('last',1,this)">
    
    		</form>		
    
      <!-- This would be for a second slideshow
    
    		<div class="imgContainer">
    			<img src="null" id="pagingImg2">
    		</div>
    
    		<div id="caption2" class="captions"></div>
    
    		<form action="">						
    					                                  			
    			<input type="button" value="<<" class="pagingBtn" alt="First" title="First" onclick="turnPage('first',2,this)">
    			<input type="button" value="<" class="pagingBtn" alt="Previous" title="Previous" onclick="turnPage('prev',2,this)">
    			<input type="button" name="slideShowBtn" value="Start" class="pagingBtn" alt="Start Slideshow" title="Start Slideshow" onclick="autoTurn(this,2,true)">
    			<input type="button" value=">" class="pagingBtn" alt="Next" title="Next" onclick="turnPage('next',2,this)">
    			<input type="button" value=">>" class="pagingBtn" alt="Last" title="Last" onclick="turnPage('last',2,this)">
    
    		</form>
      -->
    	</body>
    </html>
    
    Code (markup):
     
    Mike H., Jul 2, 2009 IP