Reputation: 1994
I am using swiper.js. I would like to always have new/active slides scroll to the top, so when a new slide enters the viewport, the content must be scrolled to the top.
I have a fiddle here: https://jsfiddle.net/p406sfe4/8/
I though that this script might accomplish what I need, but it doesn't seem to work:
swiper.on('slideChangeEnd', function(s) {
s.slides.each(function() {
if ($(this).index() !== s.activeIndex) $(this)[0].scrollTop = 0
});
});
Thanks!
Upvotes: 2
Views: 10313
Reputation: 450
Well, above answer did not work for me. Adding this answer to different scenario.
In my case I had multiple swiper on the same page with different wrapper ID and I was initializing Swiper with reference to its ID,
With multiple instances of swiper, I couldn't get to proper position of slider, so I had to it this way.
var SwiperItems= [];
$('.swiper-items-wrapper').each(function(i) {
var this_ID = $(this).attr('id');
SwiperItems[i] = new Swiper( '#' + this_ID + ' .swiper-contrainer', {
loop: true,
navigation: {
nextEl: '#' + this_ID + ' .swiper-button-next-outsite',
prevEl: '#' + this_ID + ' .swiper-button-prev-outsite',
},
autoHeight: true,
});
SwiperItems[i].on('slideChange', function (swiperObj) {
$('html, body').animate({
scrollTop: jQuery(SwiperItems[i].$el).offset().top
}, 1000);
);
});
Upvotes: 0
Reputation: 1373
Unless you're restricting the height of the container/slides - causing an overflow - the scrollable content won't actually be inside each slide.
In that case you should focus on the scrollTop
property of the swiper container or other parent element.
Regardless of what you're scrolling to, the event will work better if added to the initialization config. To use the code from your jsfiddle:
var swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
paginationClickable: true,
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev',
spaceBetween: 30,
hashnav: true,
autoHeight: true,
// attach callback here
onSlideChangeEnd: function (swiperObj) {
$('.swiper-container').css('scrollTop', '0');
}
});
Upvotes: 3