Image Cycle Application Programming Tutorial

Published :
Author :
Adam Khoury
Learn to program dynamic JavaScript thumbnail image cycling programs where the pictures automatically cycle as the user places their mouse over a preview image. Then when the user mouse leaves the image, the default image is put back in place. This sort of program can be used to cycle through a collection of video thumbnail images, to cycle product images in an online store, or for any type of situation you wish to apply it to. Note: You can externalize any JavaScript programs into a cycle.js file that your document can then call in anywhere on the page. <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Thumbnail Cycle Tutorial</title> <style> .item{ float: left; border: #AAA 1px solid; padding: 10px; margin: 10px; } .item > img{ width: 180px; height: 140px; border: #666 1px solid; cursor: pointer; } .item > span{ display: block; text-align: center; margin-top: 10px; } </style> <script> window.addEventListener("load", function(){ var items_container = document.getElementById("items_container"); var thumbtimer, ti=0, dir="item_images/"; var obj1 = { name:"Pistol", pics:["pistol_a.jpg","pistol_b.jpg","pistol_c.jpg"] }; var obj2 = { name:"Glasses", pics:["glasses_a.jpg","glasses_b.jpg","glasses_c.jpg"] }; var obj3 = { name:"Box", pics:["box_a.jpg","box_b.jpg","box_c.jpg","box_d.jpg"] }; var ary = [obj1,obj2,obj3]; for(var i=0; i < ary.length; i++){ var div = document.createElement("div"); var img = document.createElement("img"); var span = document.createElement("span"); div.className = "item"; img.oi = i; img.src = dir + ary[i].pics[0]; span.innerHTML = ary[i].name; items_container.appendChild(div); div.appendChild(img); div.appendChild(span); img.addEventListener("mouseover", function(event){ thumbtimer = setInterval(function(){ ti++; if(ti == ary[event.target.oi].pics.length){ ti = 0; } event.target.src = dir + ary[event.target.oi].pics[ti]; }, 700); }); img.addEventListener("mouseout", function(event){ clearInterval(thumbtimer); ti = 0; event.target.src = dir + ary[event.target.oi].pics[ti]; }); } }); </script> </head> <body> <div id="items_container"></div> </body> </html>