jkd
jkd

Reputation: 126

Accordion with jQuery (not jQueryUI) - there's a "DRY" way to do this.. just don't know how

Basically I want to add the class "active" to whatever (+) I click, along with changing the pseudo content from "+" to "-", then back to "+" when the "active" class is removed. I originally used the jQueryUI accordion method, but the animation wasn't completely fluid so I'm trying this route.

one = $('.first');
two = $('.second')
three =$('.third')

$('.one').click(function() {
    one.toggleClass('active');
    $(this).toggleClass('show');
});

$('.two').click(function() {
    two.toggleClass('active');
    $(this).toggleClass('show');
});

$('.three').click(function() {
    three.toggleClass('active');
    $(this).toggleClass('show');
});

Everything is fully functional in my codepen, just trying to get better at DRY jQuery.

Upvotes: 2

Views: 28

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 241198

The key is to target the shared classes. In your case, add a single click event listener to the .more elements and then when the element is clicked, toggle the .show class while selecting the previous .dropdown element and toggling the .active class.

Updated Example

Here is a simplified snippet:

$('.more').on('click', function () {
    $(this).toggleClass('show').prev('.dropdown').toggleClass('active');
});

Alternatively, you could also traverse the DOM and select the closest .price ancestor element and then select the descendant .price element and toggle the corresponding classes.

The advantage to this approach is that the code will continue to work even if the order of the elements is changed or if the nesting differs. In other words, it is more flexible and is less likely to break with future changes.

Updated Example

$('.more').on('click', function () {
    $(this).toggleClass('show')
           .closest('.price').find('.dropdown').toggleClass('active');
});

Upvotes: 2

Related Questions