Victor Victor - 7 months ago 67
Javascript Question

Nested horizontal sliders with click controls

How do I get a nested horizontal slider to work with click controls by show/hiding them.

I'm using Swiper which I have almost working except if you click / transition into the nested slider, you can't go back from that first slide without first transition one slide. If you click all the way to the end and back, it works perfectly. There are many callbacks in the Swiper api available.

My progress so far: Nested slider Fiddle

$(document).ready(function() {

var swiperH = new Swiper('.swiper-container-h', {
pagination: '.swiper-pagination-h',
paginationClickable: true,
spaceBetween: 0,
nextButton: '.h-next',
prevButton: '.h-prev',
onSlideChangeStart: function() {
if ($('.swiper-container-h .swiper-slide-active').children().hasClass('swiper-container-v')) {
console.log('nested');
$('.h-prev, .h-next').hide();
} else {
console.log('notnested');
$('.h-prev, .h-next').show();
}
},
onReachBeginning: function() {},
onReachEnd: function() {}
});

var swiperV = new Swiper('.swiper-container-v', {
pagination: '.swiper-pagination-v',
paginationClickable: true,
direction: 'horizontal',
spaceBetween: 0,
nextButton: '.v-next',
prevButton: '.v-prev',
nested: true,
onReachBeginning: function() {
$('.h-prev').show();
},
onReachEnd: function() {
$('.h-next').show();
},
onSlideChangeStart: function(slides) {
if (slides.activeIndex === 1) {
console.log('slide 2');
}
}
});

});


EDIT:

Cleaned up fiddle using @TheOnlyError 's answer here and here:

$(document).ready(function() {

var swiperH = new Swiper('.swiper-container-h', {
pagination: '.swiper-pagination-h',
paginationClickable: true,
spaceBetween: 0,
nextButton: '.h-next',
prevButton: '.h-prev',
onSlideChangeStart: function() {
if ($('.swiper-container-h .swiper-slide-active').children().hasClass('swiper-container-v')) {
$('.h-prev, .h-next').hide();
} else {
$('.h-prev, .h-next').show();
}
},
onSlideNextStart: function() {
$('.h-prev').show();
}
});

var swiperV = new Swiper('.swiper-container-v', {
pagination: '.swiper-pagination-v',
paginationClickable: true,
direction: 'horizontal',
spaceBetween: 0,
nextButton: '.v-next',
prevButton: '.v-prev',
nested: true,
onReachBeginning: function() {
$('.h-prev').show();
},
onReachEnd: function() {
$('.h-next').show();
},
});
});

Answer

The problem is that Swiper won't detect the transition between seperate Swiper objects. The solution would be checking when one has swiped to the next slide from the first horizontal one, to show the previous button.

So add this function to your first Swiper object:

onSlideNextStart: function(swiper) {
  $('.h-prev').show();
}

Check the fiddle.