I wanted to add a play/stop buttons to owl carousel. So far I managed to achive:
- Added the play/stop buttons before owl-dots
- Wrapped it all in a
div.controls
for better styling.
and this works well but only with one slider. When adding the next slider the code stops add the play/stop buttons without any errors in the consol.
I have tried to change the querySelector
to querySelectorAll
but then I get an error Uncaught TypeError: Cannot read properties of undefined (reading 'insertBefore')
It would be perfectly if I could:
- have multiple sliders with the buttons
- modify if the play/stop buttons will be added before owl-dots or owl-nav for each slider
code:
jQuery(function ($) {
$(document).ready(function () {
var owl = $('.slider__carousel');
owl.owlCarousel({
loop: true,
autoplay: true,
margin: 15,
animateIn: 'fadeIn',
animateOut: 'fadeOut',
dots: true,
responsiveClass: true,
responsive: {
0: {
items: 1,
nav: true
},
700: {
items: 1,
nav: true
},
970: {
items: 1,
nav: true
},
1000: {
items: 1,
nav: true,
}
}
});
var owl = $('.logo-slider');
owl.owlCarousel({
loop: true,
autoplay: true,
autoplayTimeout: 1000,
autoplayHoverPause: true,
margin: 15,
dots: true,
responsiveClass: true,
responsive: {
0: {
items: 4,
nav: true
},
700: {
items: 2,
nav: true
},
970: {
items: 5,
nav: true
},
1000: {
items: 6,
nav: true,
}
}
});
var target = document.querySelector('.owl-dots');
var wrapper = document.createElement('div');
wrapper.classList.add('controls');
target.parentNode.insertBefore(wrapper, target);
wrapper.appendChild(target);
document.querySelector('.owl-dots').insertAdjacentHTML('beforebegin', '<div class="owl-play-stop-btn"><a class="btn-play"><span class="visually-hidden">Play</span></a><a class="btn-stop"><span class="visually-hidden">Stop</span></a></div>');
$('.btn-play').ready(function () {
owl.addClass("hide-play");
});
$('.btn-play').on('click', function () {
owl.trigger('play.owl.autoplay', [1000]);
owl.addClass("hide-play").removeClass("hide-pause");
});
$('.btn-stop').on('click', function () {
owl.trigger('stop.owl.autoplay');
owl.addClass("hide-pause").removeClass("hide-play");
});
});
});