Link to home
Start Free TrialLog in
Avatar of crm624
crm624

asked on

I need help making a jquery slider automatic.

I have a jquery slider that slides both left and right on button clicks. Could someone help me get the slider to slide on its own with a small pause in between?  Then the buttons would override it. Do I use setInterval for the same action of the left button? My html file is below and javascript it attached.

<div class="slider">
      <ul>
            <li><img src="1.gif"></li>
            <li><img src="2.gif"></li>
            <li><img src="3.gif"></li>
            <li><img src="4.gif"></li>
      
      </ul>
</div>

<div id="slider-nav">
      <button data-dir="prev">Previous</button>
      <button data-dir="next">Next</button>
</div>
slider.js
Avatar of PCableGuy
PCableGuy
Flag of United States of America image

ASKER CERTIFIED SOLUTION
Avatar of hankknight
hankknight
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of crm624
crm624

ASKER

It is closer. Didn't do anything on the page load though. After clicking it started going back and forth quickly and eventually crashed the browser.
Try this:

var autogo;
(function($) {
	var sliderUL = $('div.slider').css('overflow', 'hidden').children('ul'),
		imgs = sliderUL.find('img'),
		imgWidth = imgs[0].width,
		imgsLen = imgs.length, 
		current = 1,
		totalImgsWidth = imgsLen * imgWidth;

	$('#slider-nav').show().find('button').on('click', function() {
		var direction = $(this).data('dir'),
			loc = imgWidth; 

		
		( direction === 'next' ) ? ++current : --current;

		
		if ( current === 0 ) {
			current = imgsLen;
			loc = totalImgsWidth - imgWidth;
			direction = 'next';
		} else if ( current - 1 === imgsLen ) { 
			current = 1;
			loc = 0;
		}

		transition(sliderUL, loc, direction);
	});

	function transition( container, loc, direction ) {
		var unit; 

		if ( direction && loc !== 0 ) {
			unit = ( direction === 'next' ) ? '-=' : '+=';
		}

		container.animate({
			'margin-left': unit ? (unit + loc) : loc
		});
	}

})(jQuery);

$(document).ready(function() {
  clearInterval(autogo);
  autoGo = setInterval("$('#slider-nav button').click();",2000);
});

Open in new window

Avatar of crm624

ASKER

It slides now but all the way to the end and back very quickly. I just need a quick pause between images now.
Avatar of crm624

ASKER

Added a class to the button and you code worked. Thanks.