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:

<li><a href="#!" class="category_btn category_btn_active" data-filter="Services">Services</a></li>
<li><a href="#!" class="category_btn" data-filter="Static">Static Website</a></li>


<div class="Services service_itembox">
    <img src="Assets/pic-1.jpg" alt="service image">
</div>

<div class="Static service_itembox">
    <img src="Assets/pic-2.jpg" alt="service image">
</div>

index.js:

$(function () {
    $(".category_btn").click(function () {
        $(this).addClass('category_btn_active').siblings().removeClass('category_btn_active')

        const value = $(this).attr('data-filter');
        if(value == "Services"){
            $('.service_itembox').show('slow');
        }else{
            $('.service_itembox').not('.'+value).hide('slow');
            $('.service_itembox').filter('.'+value).show('slow');
        }
    });
});

style.css:

.category_btn_active{
    color: white;
    border-color:gray;
    border-style:solid ;
    border-width:0px 0px 1px 0px;
    background-color: #019587;
    padding: 8px;
    font-size: 14px;
    text-transform: uppercase;
}

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/

$(function () {
    $(".category_btn").click(function () {
        $(this).addClass('category_btn_active').parent().siblings().find("a.category_btn").removeClass('category_btn_active')

        const value = $(this).attr('data-filter');
        $(`.${value}.service_itembox`).show('slow');
        $(`.service_itembox`).not('.'+value).hide('slow');
        $(`.service_itembox`).filter('.'+value).show('slow');
    });
});

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:

div.Static.service_itembox {
  display: none;
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement