Home > Back-end >  How can I add a CSS class to the button that is clicked among multiple buttons using jQuery?
How can I add a CSS class to the button that is clicked among multiple buttons using jQuery?

Time:10-19

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="#!"  data-filter="Services">Services</a></li>
<li><a href="#!"  data-filter="Static">Static Website</a></li>


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

<div >
    <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;
}

CodePudding user response:

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;
}
  • Related