I have an image gallery which works great. When the last slide is reached the image gallery just shuffles back to the first image.
Now, what I want to know is how can I disable the next or previous image when the last/first image has been reached? My code is…
Slider Script
function Slider(container, nav) {
this.container = container;
this.nav = nav.show();
this.imgs = this.container.find('img');
this.imgWidth = this.imgs[0].width;
this.imgsLen = this.imgs.length;
this.current = 0;
}
Slider.prototype.transition = function ( coords ) {
this.container.animate({
'margin-left': coords || -( this.current * this.imgWidth )
});
};
Slider.prototype.setCurrent = function( dir ) {
var pos = this.current;
pos += ( ~~( dir === 'next' ) || -1);
this.current = ( pos < 0 ) ? this.imgsLen - 1 : pos % this.imgsLen;
return pos;
};
HTML
<div class="slider">
<ul>
<li>
<img src="http://..../spacer.gif" height="400" />
</li>
<li>
<img src="http://..../spacer.gif" height="400" />
</li>
</ul>
</div>
<div id="slider-nav">
<button class="previous" data-dir="prev">Previous</button>
<button data-dir="next">Next</button>
</div>
Slider Initiation
<script>
var container = $('div.slider').css('overflow', 'hidden').children('ul');
var slider = new Slider( container, $('#slider-nav') );
slider.nav.find('button').on('click', function() {
slider.setCurrent( $(this).data('dir') );
slider.transition();
});
</script>
I understand this is probably an arse-about-face way of going about building a slider, but I’ve not been working with jQuery for long.
I’ve tried doing something along the lines of..
if (this.current = this.imgsLen - 1) {
$(':button:contains("previous")').attr('disabled', 'disabled');
}
But to no avail. I’ve googled this too, and still haven’t come up with anything which has worked.
In case you need one to play about with, heres a jsFiddle of it (ignore the fact that the image doesnt slide automatically, this is because of the li having a border!)
Ok, so you’ve got a few things going on. In this code, there are two problems
First, assignment.
this.current = this.imgsLen - 1. Notice the single=? You’re settingthis.currentwhenever the code runs.Second,
:buttonis shorthand for$("button, input[type='button']"). It’ll work but since you know you only have<botton>you might just as well use$('button')since it will be faster.Finally, the code previously submitted, but here’s another option. Change up your nav to have previous and next classes:
Then add this to your transition function:
Here’s a working version:
http://jsfiddle.net/Qqk3U/15/
Hope that helps.