I'm trying to do slider, that users can navigate it by right and left arrow of keyboard.
stackoverflow
I've recently read this question, but it seems owlcarousel's architecture have been changed.
import React from "react";
import OwlCarousel from "react-owl-carousel";
import "owl.carousel/dist/assets/owl.carousel.min.css";
import "owl.carousel/dist/assets/owl.theme.default.min.css";
function App() {
document.body.addEventListener("keydown", (event) => {
const owl = document.querySelector(".owl-theme");
console.log(event.keyCode);
if (event.keyCode === 37) {
/*left key*/
//How can I trigger prev button???
} else if (event.keyCode === 39) {
/*right key*/
//How can I trigger the next button?
}
});
return (
<>
<OwlCarousel
item="3"
nav
autoplay
className="owl-carousel owl-theme owl-loaded"
>
<div className="item">hi</div>
<div className="item">hi</div>
<div className="item">hi</div>
<div className="item">hi</div>
<div className="item">hi</div>
<div className="item">hi</div>
<div className="item">hi</div>
<div className="item">hi</div>
<div className="item">hi</div>
</OwlCarousel>
</>
);
}
export default App;
First of all you must set variable that will find your carousel:
var owl = $('.owl-carousel');
Then call trigger in this way:
// Go to the next item
$('.customNextBtn').click(function() {
owl.trigger('next.owl.carousel');
});
// Go to the previous item
$('.customPrevBtn').click(function() {
// With optional speed parameter
// Parameters has to be in square bracket '[]'
owl.trigger('prev.owl.carousel', [300]);
});
More about triggers you will find here:
https://owlcarousel2.github.io/OwlCarousel2/docs/api-events.html
Look for event with Type: triggerable
All of them can be called as owl.trigger('event-name');
Your code must be thomething as that:
if (event.keyCode === 37) {
/*left key*/
owl.trigger('prev.owl.carousel');
} else if (event.keyCode === 39) {
/*right key*/
owl.trigger('next.owl.carousel');
}
And one more thing) You detect carousel by classname: document.querySelector(".owl-theme")
So triggers will be attachhed on all carousels with this classname at the same time.
Best way will be detect owl by id - it will call triggers only in one carousel with one id. For example:
<div id="myCarousel1" class="owl-carousel owl-theme">
document.getElementById('myCarousel1');