Reputation: 459
I have made a carousel slider with jquery, where I have some products. I want the slider to stop sliding when I reach the last product, what I was able to do so far is to stop the sliding when the last product is not visible, but thats not what I need. It should stop when the last product is visible, How can I achieve that?
HTML
<div class="controls">
<div class="control-left">left</div>
<div class="control-right">right</div>
</div>
<div class="container">
<div class="sliderHolder">
<div class="productsWrapper">
<article>
<img src="http://www.sha.org/bottle/missionbottle.jpg">
</article>
<article>
<img src="http://www.sha.org/bottle/missionbottle.jpg">
</article>
<article>
<img src="http://www.sha.org/bottle/missionbottle.jpg">
</article>
<article>
<img src="http://www.sha.org/bottle/missionbottle.jpg">
</article>
<article>
<img src="http://www.sha.org/bottle/missionbottle.jpg">
</article>
<article>
<img src="http://www.sha.org/bottle/missionbottle.jpg">
</article>
</div>
</div>
</div>
JQUERY
var container = $(".sliderHolder");
var containerProducts = $(".productsWrapper").width();
var animating = false;
$(document).on("click", ".control-right", function () {
if (parseInt(container.css("right"), 10) <= containerProducts) {
animating = true;
container.stop().animate({
'right': "+=401px"
}, 600, function () {
animating = false;
});
}
});
$(document).on("click", ".control-left", function () {debugger;
if (parseInt(container.css("right"), 10) > 0) {
animating = true;
container.stop().animate({
'right': "-=401px"
}, 600, function () {
animating = false;
});
}
});
$(".control-left, .control-right").click(function () {
if (animating) {
return false;
}
});
CSS
.controls {
top: 50px;
width: 100%;
height: 100px;
position:relative;
}
.control-left {
left:0;
}
.control-right {
right:0;
}
.control-left, .control-right {
width: 50px;
height: 50px;
background-color: #000;
position: absolute;
color: #fff;
}
.container {
max-width: 100%;
overflow: hidden;
position: relative;
}
.productsWrapper {
display: inline-block;
}
.sliderHolder {
position:relative;
width: 28000px;
right: 0px;
}
img {
width: 200px;
}
article {
width: 200px !important;
float: left;
}
Upvotes: 0
Views: 490
Reputation: 413
If your articles are always 200px, and you slide it 2 articles at the time, your if
-statement should be if (parseInt(container.css("right"), 10) <= (containerProducts - 400))
This way, it checks if two more would fit. If not, it will not animate.
You should try to make it a bit more dynamic, though. But this answers your question.
(fiddle: https://jsfiddle.net/3zcn19ms/5/)
Hey, because of the comment you gave below this answer, I changed the code a bit. See if this helps you out:
https://jsfiddle.net/3zcn19ms/22/
Now using the size of the first image (this is only correct if all pictures have the exact same width) and the amount of articles in your wrapper.
Upvotes: 1