Web Info and IT Lessons Blog...

Friday 29 May 2015

Simple Javascript Slider

The previous lesson of javascript lessons series was about Javascript Keyboard Events and in this lesson we will learn to make a simple slider in javascript.

Simple Javascript Slider

Demo: Make a Simple Slider in Javascript



In the html part of the slider, all we need is a simple div element i.e

Html Code:

<div id="slider"></div>

The css part of the slider is used to style the slider div i.e

Css Code:

#slider{
   width:510px;
   height:310px;
   border:2px solid #2f3430;
   margin-bottom:21px;
   margin-left:23px;
   cursor:pointer;
}

The main part of the slider is the javascript part. Javascript code of the slider is given below:

Javascript Code:

<script type="text/javascript">
window.addEventListener("load",startSlider,false);
var _count = 0, _a = 0, imagearrlen, _flag = 1, _flagcount = 0, interval;
var initSliderWidth = 510;         // width of the slider image
var initSliderHeight = 310;        // height of the slider image
var imagearr = [];
imagearr[0] = "http://1.bp.blogspot.com/-77XLdTJSclA/VUn-myYQNtI/
               AAAAAAAAA2A/k74NfsAPueM/s1600/array.jpg";
imagearr[1] = "http://3.bp.blogspot.com/-rTL7Gj1mdIs/VUn_ymxSgGI/
               AAAAAAAAA2Q/4UymHbvl9bo/s1600/mysql-delete-query.jpg";
// add a new image here at index imagearr[2]

function startSlider(){
 setInterval(function (){imageSlider();}, 100);
}

function imageSlider(){
 var slider = document.getElementById("slider");
 imagearrlen = imagearr.length;
 if(_count == 0 && _flag == 1){
  if(slider != null){
   slider.innerHTML = "";
   var img = new Image();
   img.src = imagearr[_a];
   img.width = initSliderWidth;
   img.height = initSliderHeight;
   img.id = "image";
   img.style.opacity = 0;
   slider.appendChild(img);
   _count++;
  }
 }else if(_count <= 10 && _count > 0 && _flag == 1){
  
  var img = document.getElementById("image");
  if(img != null){
   img.style.opacity = _count*0.1;
   _count++;
  }
 }else if(_count == 11 && _flag == 1){
  _flag = 0;
  timeset();
  _count++;
 }else if(_count > 11 && _count <= 21 && _flag == 1){
  var img = document.getElementById("image");
  if(img != null){
   img.style.opacity = img.style.opacity - 0.1;
   if(img.style.opacity < 0.15){
    img.style.opacity = 0;
   }
   _count++;
  }
 }else if(_count == 22){
  _count = 0;
  _a++;
  if(_a == imagearrlen){
   _a = 0;
  }
 }
}

function startcount(){
 if(_flagcount == 3){
 
  _flagcount = 0;
  _flag = 1;
  clearInterval(interval);
 
 }else{
 _flagcount++;
 }
}

function timeset(){
 interval = setInterval(function (){startcount();}, 1000);
}
</script>

The paths of images are saved in an array i.e imagearr[]. To add a new image to the slider save the path of the image at the last array index.

initSliderWidth and initSliderHeight are the width and height of the image displayed in the slider respectively.

Stay tuned for more lessons...

No comments:

Post a Comment