javascript - How to create a simple slider? -
i have build following carousel when reach last image or first image want go want show image needs show. example when reach last image when click right arrow show first image.
have idea how improve this?
https://jsfiddle.net/6nhuk7vm/
jquery(document).ready(function ($) { var currentposition = 0; var slidewidth = 1200; var slides = $('.slide'); var numberofslides = slides.length; var slideshowinterval; var speed = 7000; slideshowinterval = setinterval(changeposition, speed); slides.wrapall('<div id="slidesholder"></div>') slides.css({ 'float' : 'left' }); $('#slidesholder').css('width', slidewidth * numberofslides); $('#slideshow') .append('<span class="nav" id="leftnav"></span>') .append('<span class="nav" id="rightnav"></span>'); managenav(currentposition); $('.nav').bind('click', function() { currentposition = ($(this).attr('id')=='rightnav') ? currentposition+1 : currentposition-1; managenav(currentposition); clearinterval(slideshowinterval); slideshowinterval = setinterval(changeposition, speed); moveslide(); }); function managenav(position) { $('#leftnav').css('position','absolute') $('#rightnav').css('position','absolute') } function changeposition() { if(currentposition == numberofslides - 1) { currentposition = 0; managenav(currentposition); } else { currentposition++; managenav(currentposition); } moveslide(); } function moveslide() { $('#slidesholder') .animate({'marginleft' : slidewidth*(-currentposition)}); } });
the standard way make 'carousel' effect, 'wrap' around right/left side of system, use modulo %
.
consider code:
currentposition = ($(this).attr('id')=='rightnav') ? currentposition+1 : currentposition-1;
that adds position right, , removes 1 left. now, need "bound/wrap" inside limits. easy, with:
currentposition = (currentposition + numberofslides) % numberofslides;
what do?
if currentposition -1, adds full amount, , end numberofslides - 1
, modulo has no effect.
if currentposition more 0 become larger-than-numberofslides value, , modulo (remainder) function restore it's proper value.
Comments
Post a Comment