I have a Swiper.js carousel that autoplays. I also fade in my page using DOMContentLoaded. This means that the first slide has changed or is in the middle of changing when the page comes into view. So it's in view a much shorter amount of time compared to the others.
Is it possible to delay the initial running of the autoplay carousel? I know you can add a delay to individual slides - but if I do that to counter it, it means 2nd time around the first slide lags/is in view longer than the rest.
JavaScript code:
window.addEventListener('DOMContentLoaded', function() {
document.body.className = 'visible';
});
var caption = document.querySelector('.swiper-caption span');
new Swiper('.swiper', {
// Disable preloading of all images
preloadImages: true,
// Enable lazy loading
lazy: false,
effect: 'fade',
fadeEffect: {
crossFade: true
},
loop: true,
autoplay: {
delay: 1200,
disableOnInteraction: false,
pauseOnMouseEnter: true
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev'
},
pagination: {
el: '.swiper-pagination',
type: 'fraction'
},
on: {
init: function() {
updateCaptionText(this);
},
activeIndexChange: function() {
updateCaptionText(this);
}
}
});
function updateCaptionText(slider) {
caption.textContent = slider.slides[slider.activeIndex].dataset.caption;
}
CSS code:
body.hidden {
opacity: 0;
}
body.visible {
opacity: 1;
transition: opacity .48s .24s ease-out;
}
Call swiper.autoplay.stop() just after setting it up, and call swiper.autoplay.start() inside DOMContentLoaded event handler. Like so:
const swiper = new Swiper(".swiper", {
// Disable preloading of all images
preloadImages: true,
// Enable lazy loading
lazy: false,
effect: "fade",
fadeEffect: {
crossFade: true,
},
loop: true,
autoplay: {
delay: 1200,
disableOnInteraction: false,
pauseOnMouseEnter: true,
},
navigation: {
nextEl: ".swiper-button-next",
prevEl: ".swiper-button-prev",
},
pagination: {
el: ".swiper-pagination",
type: "fraction",
},
on: {
init: function () {
updateCaptionText(this);
},
activeIndexChange: function () {
updateCaptionText(this);
},
},
});
swiper.autoplay.stop();
window.addEventListener("DOMContentLoaded", () => {
document.body.className = "visible";
swiper.autoplay.start();
});
If you wanna delay the inital start even further, to match it with your CSS animation duration, you can use a setTimout, like this:
window.addEventListener("DOMContentLoaded", () => {
document.body.className = "visible";
setTimeout(() => swiper.autoplay.start(), 1000); // 1000 means 1s, it's in ms here.
});
Live example here at this CodePen I forked. References of used methods are here on Swiper.js's official doc.
Related
So I want to do this swiper.js carousel which slides linear from right to the left and after mouse hover it would stop. I used this function which works pretty fine:
$(".swiper-container3").hover(function() {
(this).swiper.autoplay.stop();
}, function() {
(this).swiper.autoplay.start();
});
If speed parameter is not defined in my swiper initialization function, then it stops after a hover (but only if the nearest slider will be on center of carousel).
How to force swiper.js to stop with the function above but not to wait for one of the sliders to be on center?
Rest of the code
const enableSwiper3 = function(){
mySwiper3 = new Swiper ('#swiper-container3', {
loop: true,
slidesPerView: "auto",
spaceBetween: 10,
centeredSlides: true,
a11y: true,
keyboardControl: true,
grabCursor: true,
freeMode: false,
pagination: {
el: '#swiper-pagination3',
},
paginationClickable: true,
breakpoints: {
400: {
slidesPerView: 'auto',
spaceBetween: 20,
loop: true
},
767: {
autoplay: {
delay: 5000,
disableOnInteraction: true,
pauseOnMouseEnter: true,
},
speed: 10000,
}
}
});
mySwiper3.autoplay.start();
}
I also want to lower its speed so whole slider goes linear very slow and just after hovering it it stops. Example on the site below: https://www.intercom.com/ (people are talking section).
const onToggle = (id) => {
setActive(id === active ? null : id);
scroller.scrollTo(id, {
smooth: true,
duration: 500,
spy: true,
exact: true,
offset: -15,
});
};
How do I set a 0.5s delay before scroller.scrollTo starts running? I need it to wait before it decides where to scroll.
If you want delay 0.5s, you can use setTimeout:
setTimeout(() => {
scroller.scrollTo(id, {
smooth: true,
duration: 500,
spy: true,
exact: true,
offset: -15,
});
}, 500);
I have four buttons to show/hide slide card based on user selection. I show all products by default in total 10 cards. When changed to other options (the slide that only have four cards), there is a white space left. I tried to update with $productSlider.update() but it didn't work.
Demo Code (codesandbox)
Swiper Init
let $productSlider = new Swiper('.plan-slider-container', {
init: false,
observer: true,
observeParents: true,
observeSlideChildren: true,
spaceBetween: 0,
mousewheel: {
releaseOnEdges: true,
forceToAxis: true
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
keyboard: true,
scrollbar: {
el: '.swiper-scrollbar',
draggable: true,
hide: false,
},
breakpoints: {
320: {
slidesPerView: 1,
},
768: {
freeMode: true,
slidesPerView: 'auto'
}
}
});
User Selection Button
$('.choice-plan-btn-wrapper.desktop').on('click', e => {
let target = e.target;
let id = target.getAttribute('id');
let $parent = $(target).parent();
let lastActiveSiblingId = $(target).siblings('.active').attr('id');
if (target.tagName.toLowerCase() != 'button' || target.classList.contains('active')) return;
// button
$(target).addClass('active')
.siblings('.active').removeClass('active');
/* The Problem */
$parent.siblings('.plans-swiper-wrapper')
.children(`.${id}`).fadeIn('slow')
.siblings().not(`.${id}`).fadeOut('slow');
$productSlider.update();
/* The Problem */
$parent.siblings('.swiper-scrollbar')
.removeClass(`${lastActiveSiblingId}`)
.addClass(`${id}`)
$productSlider.slideTo(0, 500);
});
I'm using the Swiper.js library and I have an issue getting the 'slideChange' event to trigger when dynamically loading elements through JavaScript.
Here is where my swipers both horizontal and vertical are initialised:
var swiper = {
initialize : function() {
swiperH = new Swiper('.swiper-container-h', {
slidesPerView: 1,
preloadImages: false,
updateOnImagesReady: true,
lazy: true,
})
.on('slideChange', function () {
console.log('Swiped Horizonally');
});
swiperV = new Swiper('.swiper-container-v', {
direction: 'vertical',
slidesPerView: 1,
preloadImages: false,
updateOnImagesReady: true,
lazy: true,
effect: 'fade',
loop: true,
fadeEffect: {
crossFade: true
},
pagination: {
el: '.swiper-pagination-v',
clickable: true,
},
})
.on('slideChange', function () {
console.log('Swiped Vertically');
});
}
};
The reason why the horizontal's 'slideChange' triggers is because its already in the html file:
<!-- Swiper -->
<div class="dash-container">
<div class="swiper-container swiper-container-h">
<div class="swiper-wrapper" id="swipeData">
</div>
</div>
</div>
Now, the vertical slides are loading through JavaScript and that's where the vertical's 'slideChange' doesn't trigger.
function loadDresses(selectedDresses) {
return new Promise((resolve, reject) => {
$('#swipeData').html('');
for (var i = 0; i < selectedDresses.length; i++) {
var vScroll = '<div class="swiper-slide"><div class="swiper-container swiper-container-v"><div class="swiper-wrapper" style="height: 100%;">';
for (var j = 0; j < selectedDresses[i].images.length; j++) {
vScroll += '<div class="swiper-slide"><img src="' + selectedDresses[i].images[j] + '"/></div>';
}
vScroll += '<div class="swiper-slide" style="display:table;height:100%;width:100%;">';
vScroll += '</div></div></div><div class="swiper-pagination swiper-pagination-v">';
$('#swipeData').append(vScroll).trigger('create');
}
resolve(true);
});
}
The error occurs at this snippet:
.on('slideChange', function () {
console.log('Swiped Vertically');
});
Any ideas? Thanks!
Edit:
I have tried the following to stop it from initialising too early, but still no luck:
loadDresses(dresses).then(function(result) {
var t = setInterval(() => {
swiper.initialize();
clearInterval(t);
}, 5000);
});
And doesn't that help?
var swiper = {
initialize : function() {
swiperH = new Swiper('.swiper-container-h', {
slidesPerView: 1,
preloadImages: false,
updateOnImagesReady: true,
lazy: true,
})
.on('slideChange', function () {
console.log('Swiped Horizonally');
});
swiperV = new Swiper('.swiper-container-v', {
direction: 'vertical',
slidesPerView: 1,
preloadImages: false,
updateOnImagesReady: true,
lazy: true,
effect: 'fade',
loop: true,
fadeEffect: {
crossFade: true
},
pagination: {
el: '.swiper-pagination-v',
clickable: true,
},
on: {
slideChange: function() {
console.log('Swiped Vertically');
}
}
});
}
};
You have some options here:
To keep the flow of your application, you can destroy the slider and reinitialize it.
swiperH.destroy()
then
loadDresses();
swiper.initialize();
OR
you can just mySwiper.update() every time you change your slide manually
The problem is that an element with class swiper-pagination-v is not found during initialization.
You can make condition for class swiper-pagination-v exists.
var swiper = {
initialize : function() {
swiperH = new Swiper('.swiper-container-h', {
slidesPerView: 1,
preloadImages: false,
updateOnImagesReady: true,
lazy: true,
})
.on('slideChange', function () {
console.log('Swiped Horizonally');
});
if ($('.swiper-container-v').length > 0) {
swiperV = new Swiper('.swiper-container-v', {
direction: 'vertical',
slidesPerView: 1,
preloadImages: false,
updateOnImagesReady: true,
lazy: true,
effect: 'fade',
loop: true,
fadeEffect: {
crossFade: true
},
pagination: {
el: '.swiper-pagination-v',
clickable: true,
},
})
.on('slideChange', function () {
console.log('Swiped Vertically');
});
}
}
};
I'm having trouble with a carousel.
I want to add a pause or a stop event to a carousel.
I already have built a slider, on the left side you have a navigation page for the sliders.
The slider starts automatically, I want it to stop if I choose a slide manually
Here's my code:
Thanks for any hints.
jQuery(this).parent().find('.navigation>ul>li').eq(0).addClass('active').end().each(function(){
jQuery(this).on('click', function(){
jQuery(this).parents('.csc-slider').find('.pager>a').eq(jQuery(this).index()).trigger('click');
return false;
});
});
var swidth = jQuery(this).width();
jQuery(this).find('img')
.width(swidth +'px !important')
.eq(0)
.imagesLoaded()
.done(function($images){
jQuery($images).parents('.slideshow')
.find('.item')
.css({display:'block', float:'left'})
.end()
.carouFredSel({
width: "100%",
height: "variable",
items: {
visible: 1,
height: "auto"
},
scroll: {
fx : "crossfade",
duration : 5000,
onAfter:function(data) {
var p = jQuery(this).parents('.csc-slider');
var i = p.find('.pager>a.selected').index();
p.find('li.active').removeClass('active');
p.find('.navigation>ul>li').eq(i).addClass('active');
}},
auto: {
pauseOnHover: "resume",
pauseOnEvent: true,
timeoutDuration: 5000,
},
prev: {
button: jQuery($images).parents('.csc-slider').find('.prev'),
},
next: {
button: jQuery($images).parents('.csc-slider').find('.next'),
},
pagination: jQuery($images).parents('.csc-slider').find('.pager'),
});
You can add a click event to navigation buttons to stop the auto scrolling:
$(".slider-pages .prev, .slider-pages .next, .slider-nav a").click(function(){
carouFredselObject.trigger("configuration", {auto: false});
});