EDIT: posted on jsfiddle to make it easier to help out: http://jsfiddle.net/GXf45/
I’ve been able to create a slide show (thru the use of tutorials and stack overflow) and now I’m working on adding some functionality; a button for each slide in the show.
the previous and next buttons work perfectly (especially on the first and last slides) but I’m having issues with the intermediate buttons. Later I imagine the jquery adding buttons based on the number of slides.
The code below is just one of the revisions i’m working on. I’m thinking there are LOTS of opportunities to improve what i have. Let me know where my errors are and what you may do to clean this up. Thanks.
The html has some ruby at the beginning which populates a div based on some partials.
html:
<div class='slider'>
<ul>
<% Dir["app/views/main/show/*"].each do |file| %>
<li><%= render :file => Rails.root.join(file).to_s %></li>
<% end %>
</ul>
</div>
<div id='slider-nav'>
<button data-dir='prev'>Prvious</button>
<button data-dir='next'>Next</button>
<button data-dir='1'>1</button>
<button data-dir='2'>2</button>
<button data-dir='3'>3</button>
<button data-dir='4'>4</button>
</div>
js:
$(document).ready(function(){
var sliderUL = $('div.slider').css('overflow', 'hidden').children('ul'),
imgs = $('.showScene'),
imgWidth = $('.showScene').width(),
imgsLen = imgs.length,
current = 1,
totalImgsWidth = imgsLen * imgWidth;
$('#slider-nav').show().find('button').on('click', function(){
var direction = $(this).data('dir'),
loc = imgWidth;
//update current value
//(direction == 'next' ) ? ++current : --current;
if (direction == 'next')
{
current += 1; //2
}
else if (direction == 'prev')
{
current -= 1;//0
}
else
{
current = direction;
}
//if first image
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; //-= or +=
if ( direction && loc !== 0) {
unit = ( direction == 'next') ? '-=' : '+=';
}
container.animate({
'margin-left': unit ? (unit + loc) : loc
});
};
});
css:
*{margin:0px;padding: 0px;}
.showScene{
width: 800px;
height: 300px;
}
#slider-nav{
margin-top: 1em;
display: none;
}
#slider-nav button{
padding: 1em;
margin-right: 1em;
border-radius: 10px;
cursor: pointer;
}
.slider{
width: 800px;
height: 300px;
border: 2px solid grey;
overflow: scroll;
}
.slider ul {
width: 10000px;
list-style: none;
}
.slider ul li{
float:left;
list-style-type: none;
}
You’re missing the logic that works out the
locanddirectionparameters for the numbered buttons. Here is the main snippet, note I refactored your code a little to reuse the sliding logic. You just needed to work out how much you need to slide by from your current position, and which direction to slide.Try this fiddle.