alt-rock alt-rock - 20 days ago 5
CSS Question

Call jquery event handler out of scope

I am trying to call a function to add class

hover
to a link outside the scope of the carousel when an image inside has the class
active
. The active class iterates over each
item
, toggling on and off every
3 sec
.

How can i add the class when the item is active?

JS FIDDLE LINK
jsfiddle.net/vnpm1y06/222



var test = $('.active');

function linkHover() {
if ($('.item.active').length != 0) {
$('#link3').addClass('hover');
}
};
linkHover();

.hover {
color: red
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="carousel">
<div id="slide1" class="item">
<img src="img1.jpg">
</div>
<div id="slide2" class="item">
<img src="img2.jpg">
</div>
<div id="slide3" class="item active">
<img src="img3.jpg">
</div>
</div>
<div class="nav-links">
<a id="link1">Link</a>
<a id="link2">Link</a>
<a id="link3">Link</a>
</div>




Answer

Since you are using owl-carousel, you should not find a way to call something out of scope, you should look for ways to capture events and then add your code on those events.

You can check owl carousel - event docs for events and their signature.

In your case, you need change event:

owl.on('changed.owl.carousel', function(event) {
    ...
})

Now as per your fiddle, I have added an extra link as you have 5 sliding divs and 4 links.

You can refer following JSFiddle for working demo.

I'll try to find a better and more generic way to get current element's index. You can use $('.link.active').removeClass('hover').next().addClass('hover'), but this will need more refining.

Let me know if you have any queries.

Comments