Home > Net >  Prevent toggleClass to be used on every element on the page
Prevent toggleClass to be used on every element on the page

Time:04-16

I have a function which, when clicking on a link with the class .show-more, opens up the div with the class .productinfo. Now, it also adds a class to the link itself (.active) - the problem what I have is that I have a few links on this page with the same class. I've managed to only open up the correct .productinfo when clicking on it, but the class will be added to every link nonetheless. Also tried adding the following to the code but that did not work:

$(this).find('show-more').toggleClass("active");

My structure is the following:

<div >
<div >Content 1</div>
<div >Content 2</div>
<div ><a >Show more</a></div>
<div >This content is hidden and will be shown when clicked</div>
</div>

<div >
<div >Content 1</div>
<div >Content 2</div>
<div ><a >Show more</a></div>
<div >This content is hidden and will be shown when clicked</div>
</div>

jQuery(document).ready(function($) {

            $('body').on('click', 'a.show-more', function(e) {
            e.preventDefault();
            $('.show-more').toggleClass("active");
            var $this = $(this).parents('.product');
            $this.find('.productinfo').toggle(0, 'slide')

});

});

CodePudding user response:

Why not: $('a.show-more').on('click', function(e)

and then $(this).toggleClass("active");

  • Related