Reputation: 703
I have an owl carousel with various boxes rotating.
When I click on a button within the box, I want to toggle a class to a div within the same box.
It works fine when until i wrap it in an owl carousel and initialise it. After that the toggleClass method (and any other method seemingly) seems to stop working.
$(document).ready(function() {
$('.view-offer').click(function() {
var linkID = $(this).data('id')
var el = '#box-' + linkID
$(el).toggleClass('test');
console.log(el);
});
$(".offers-slider").owlCarousel({
nav: false,
autoPlay: false,
navText: [
"<i class='fa fa-angle-left'></i>",
"<i class='fa fa-angle-right'></i>"
],
loop: true,
dots: false,
items: 3
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.min.css" rel="stylesheet" />
<div class="owl-carousel owl-theme offers-slider">
<div class="item">
<a href="#!" class="view-offer" data-id="1">View</a>
<div id="box-1">
Box 1
</div>
</div>
<div class="item">
<a href="#!" class="view-offer" data-id="2">View</a>
<div id="box-2">
Box 2
</div>
</div>
<div class="item">
<a href="#!" class="view-offer" data-id="3">View</a>
<div id="box-3">
Box 3
</div>
</div>
</div>
linkID will log to the console fine but the class will not add to element. There are no errors at all.
Upvotes: 2
Views: 1023
Reputation: 3393
Every element in the Carousel has the same list of the box that means if you have tree boxes each item in the Carousel while containing #box-1
and #box-2
and #box-3
. So you need to get the closest box to your link:
$(document).ready(function() {
$('.view-offer').click(function() {
var linkID = $(this).data('id')
var el = '#box-' + linkID
$(this).siblings(el).toggleClass('test');
console.log(el);
});
$(".offers-slider").owlCarousel({
nav: false,
autoPlay: false,
navText: [
"<i class='fa fa-angle-left'></i>",
"<i class='fa fa-angle-right'></i>"
],
loop: true,
dots: false,
items: 3
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.min.css" rel="stylesheet" />
<div class="owl-carousel owl-theme offers-slider">
<div class="item">
<a href="#!" class="view-offer" data-id="1">View</a>
<div id="box-1">
Box 1
</div>
</div>
<div class="item">
<a href="#!" class="view-offer" data-id="2">View</a>
<div id="box-2">
Box 2
</div>
</div>
<div class="item">
<a href="#!" class="view-offer" data-id="3">View</a>
<div id="box-3">
Box 3
</div>
</div>
</div>
Upvotes: 2