Follow us on - Dribbble | Twitter | Facebook

Simple javascript slider

Simple Javascript Slider

In this tutorial, we have to see about simple Javascript slider/carousel. In dribbble, I have seen different types of animation for the slider which animated using SVG, motion graphics and so on. So I am trying to make a different animation for the slider. At first, I need basic animation for the slider here is the demo. In future, I’ll post different kinds of the slider will be updated. Let’s see the simple Javascript slider.

Demo

Code Contains

  • HTML
  • CSS, Transition
  • Javascript

HTML

Create HTML structure for the slider.

<div class="container" id="container">
<div class="slider-container" id="sliderContainer" data-slide="0" style="transform: translateX(0px)"> 
<div class="slider"></div> 
<div class="slider"></div> 
<div class="slider"></div> 
<div class="slider"></div> 
<div class="slider"></div> 
</div>
</div>

Add Navigation arraow “left” and “right”

<div class="navigation"> 
<span class="nav-prev" id="prev"></span> 
<span class="nav-next" id="next"></span>
</div>

Javascript

window.onload = function(){
windowWt = window.innerWidth;
windowHt = window.innerHeight;

container = document.getElementById("container");
sliderContainer = document.getElementById("sliderContainer");
sliderLength = sliderContainer.children.length;
sections = sliderContainer.children;

var totalWidth = sliderLength * windowWt;
container.style.width = windowWt+"px";
sliderContainer.style.width = totalWidth+"px";
container.style.height = windowHt+"px";

for(i=0; i<sliderLength; i++){
sections[i].style.width = windowWt+"px";
sections[i].style.height = windowHt+"px";
}

initSlider();

}

Add event and action for next and previous arrow using initSlider function.

function initSlider(){
	prevElm = document.getElementById("prev");
	nextElm = document.getElementById("next");
	
	prevElm.addEventListener("click", function(){
		var slideNum = parseInt(sliderContainer.getAttribute("data-slide"))-1;
		if(slideNum < 0){return false;} var transX = -(slideNum*windowWt); sliderContainer.style.transform = "translateX("+transX+"px)" sliderContainer.setAttribute("data-slide", slideNum); }, false); nextElm.addEventListener("click", function(){ var slideNum = parseInt(sliderContainer.getAttribute("data-slide"))+1; if(slideNum >= sliderLength){return false;}
		var transX = -(slideNum*windowWt);
		
		sliderContainer.style.transform = "translateX("+transX+"px)";
		sliderContainer.setAttribute("data-slide", slideNum);
	}, false);
}

Demo

Thank you for reading this tutorial, and if you have any queries feel free to ask. If you need any tutoial raise the request using Request Tutorial form.

You may also like