What is the best way to apply a CSS class to the button that has been clicked when there are multiple buttons using jQuery?

My goal is to display specific cards when a particular button is clicked, adding a class called category_btn_active to the clicked button. For example, if the user clicks on "Services", then the service cards will be shown. The filtering functionality works fine, but the issue arises with the line

$(this).addClass('category_btn_active').siblings().removeClass('category_btn_active')
. The problem is that the category_btn_active class remains on both buttons when another button is clicked. I want the class to only be added to the last clicked button. Where could the problem lie and what could be a suitable 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;
}

Answer №1

While this approach may not be the most elegant, it effectively demonstrates the use of parent() and sibling(), two concepts that you were previously 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');
    });
});

Please note that I have eliminated the need for your if/else statement. By organizing your classes and JavaScript logic appropriately, you can convey your intentions without relying on conditional statements.

I have also set one of your images to default as hidden during initialization, assuming that is your desired behavior:

div.Static.service_itembox {
  display: none;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for seamless integration of Crashlytics with your React Native application

As I work on developing my app with React Native, I am looking to capture crashes that occur on both the Objective-C and JavaScript aspects of the application. After following Crashlytics SDK's installation guide, I successfully implemented it into m ...

How can I add a channel to a category using await(discord.js)?

Having trouble organizing a new channel within a category. The .setParent(categoryID) method seems to only work with existing channels, causing an issue when I attempt to execute my code. Take a look at the code snippet below: client.on("message" ...

Running Handlebars using NodeJS can sometimes result in a "Cannot find module './parser'" error

After successfully creating and implementing a Handlebars template in the Browser, my next goal is to utilize the Handlebars precompiler, which requires a NodeJS module. I have already downloaded Handlebars for NodeJS along with all dependencies locally (n ...

Fade-in animation of a clock on an SVG image

I am trying to achieve a unique fade-in effect for an SVG image in my HTML. The challenge is to make the fade-in start from the top of the image and progress in a circular motion until it completes a full circle. An example of the effect I am aiming for is ...

Ways to alter the color of an icon when hovering over it

Is there a way to change the color of a material icon inside an IconButton material component when hovering over the IconButton? I've tried adding a class directly to the icon, but it only works when hovering over the icon itself and not the IconButto ...

Having trouble displaying database model information in the template

My challenge is displaying information from the Django third model (class Jenkinsjobsinformation) in the template. I've been successful in showcasing data from the first and second models (Projectname and Jenkinsjobsname). See below for a snippet of m ...

Customize the background color of InfoBox in Google Maps API V3 using a dropdown menu

I'm attempting to dynamically change the background color of an InfoBox by using a Dropdown list (this InfoBox is used to create map labels). I am using google.maps.event.addDomListener, but the values are not returning. Below is my code, can anyone i ...

How can I eliminate the need for 'library-preload.json' in my SAPUI5 application?

I am currently in the process of developing a SAPUI5 mobile application using cordova. The next step is to integrate another library, specifically cordova-plugin-file, into my project. However, I have encountered an issue where including this plugin causes ...

Implement a click event for the X-Axis label in Angular 2 Highcharts

I'm currently facing a challenge with hand-rolling a solution that involves adding a click listener to an X-Axis label in a column chart using the HighCharts API within an Angular 2+ application. Here is what I have gathered so far: I am utilizing ...

Obtaining the Initial Values of a jQueryUI Slider

I have integrated the jQueryUI slider into my project and need to show the minimum and maximum values of the slider in two separate div elements. These divs should update as the user interacts with the slider, and also display the initial values of the sli ...

What steps are involved in generating a scene dynamically with A-Frame?

Looking to transition from declarative coding in js and html to a programmatic approach with Aframe? You might be wondering if it's possible to modify your scene dynamically, here is an example of what you're trying to achieve: <!DOCTYPE html ...

When attempting to submit a record at http://localhost:5173/, a 404 (Not Found) error was

Currently, I am attempting to retrieve username data and timeTaken from a form. My goal is to send this data to my server, create the User object, and store it in MongoDB Atlas. Unfortunately, I am encountering a 404 error that I am struggling to resolve. ...

Ways to change the row height of the dropdown list according to the information in the second column?

I utilized the selectMenu jQuery widget to create a dropdown list and then incorporated it into Angular to build a reusable dropdown component. The issue I am currently dealing with is related to the height adjustment of the columns within each row of the ...

Is it possible to have a field automatically calculate its value based on another field?

Consider the following data structure: { "rating": 0, "reviews": [ {"name": "alice", rating: 4}, {"name": "david", rating: 2} ] } What is the best way to recalculate the overall rating when new reviews are added or existing reviews are upda ...

Restore the onblur attribute after deleting it

I am facing an issue with a textbox that utilizes onblur and ondblclick events. When the user double clicks, it triggers a pop-up screen but I do not want the onblur event to be activated. To prevent the onblur event from triggering when double-clicking, ...

Flattening an array of Map in Typescript involves combining all the

I am working with an array containing entries of type Map<string, number> Is there a way to flatten this array into a single map? Map<string, number>[] converted to Map<string, number> Appreciate any help on this matter. ...

Having trouble with Laravel 5.8 Bootstrap integration within JQuery?

i found a helpful resource at everything seems to be working well in the view, but i'm encountering issues when trying to implement it in JQuery. if anyone has suggestions on how to resolve this problem, please let me know. here is the PHP code for ...

Tips for effectively implementing an Ajax request with JavaScript when the page loads

I have been developing a shopping cart application that utilizes local storage to store the items added by users. The challenge I'm currently facing is populating the page with the user's cart items stored in local storage when they navigate away ...

Using the `this` pointer in the fs.readFile function in Node.js

I want to load a list of objects from a file using the fs.readFile method with the use of the this keyword in my JavaScript class var MyReaderClass = (function() { //Const function MyReaderClass() { this.readObjects = []; /** ...

How to properly size a child div inside a parent container

I'm having trouble with sizing a child div inside a parent div. The problem is that the child div's size changes according to the number of elements it contains, but I want all the child divs to be the same size regardless. This issue arises with ...