Skip to content
Advertisement

How can I add a CSS class to the button that is clicked among multiple buttons using jQuery?

My motive is when someone will click on a particular button then will show the particular cards and will add a class named category_btn_active that clicked. Suppose Services will be clicked then the service cards will be shown. Here the filtering is working well, the problem is here $(this).addClass('category_btn_active').siblings().removeClass('category_btn_active'). The category_btn_active class adds when clicked but when I clicked another button it stays in both buttons. I want the class will be added to just the last clicked button. Where is the problem? give a relevant solution…

index.html:

JavaScript

index.js:

JavaScript

style.css:

JavaScript

Advertisement

Answer

This is not the most elegant way to do this, but it illustrates use of parent() and sibling(), which you were struggling with:

https://jsfiddle.net/v5fg3qwh/2/

JavaScript

Note that I removed your if/else because you don’t need it. Your classes and JS logic are defined in such a way that you can specify your intent w/out those conditionals.

I also defaulted one of your images to be hidden at initialization, which I assume is what you’d want:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement