Adding classes conditionally with jQuery

Currently, I am working on a frontend project that involves jQuery. I have a list of names and I want to add a class of "selected" when one is clicked. However, if another name is selected, the class should be removed from the previously selected name and added to the new selection. Since there are multiple names, creating individual functions for each option is not feasible. Is there an easier way to achieve this functionality?

HTML

 <ul class="names">
                    <li class="name selected">Name-1</li>
                    <li class="name">Name-2</li>
                    <li class="name">Name-3</li>
                </ul>

CSS

.selected {
    background-color: rgba(0, 0, 0, 0.3);
}

Answer №1

To achieve this functionality, follow these steps:

$("ul.items li").on("click", function(){
   $("ul.items li").removeClass("active");
   $(this).addClass("active");
})

UPDATE - clarification In the provided code snippet, the selection of all <li> elements within the ul.items is targeted. Subsequently, the script removes the active class from all li tags using

$("ul.items li").removeClass("active");
, followed by adding the active class specifically to the clicked li element denoted by the this keyword.

$("ul.items li").on("click", function() {
  $("ul.items li").removeClass("active");
  $(this).addClass("active");
})
.active {
  background-color: rgba(0, 0, 0, 0.3);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="items">
  <li class="item active">Item-1</li>
  <li class="item">Item-2</li>
  <li class="item">Item-3</li>
</ul>

Answer №2

If you're looking for a solution, try this approach.

$('.name').on('click', function() {
  $('.name').removeClass('selected').css('background','none');
  $(this).addClass('selected').css('background',$(this).data('bg'));
});
$('.name.selected').css('background',$('.name.selected').data('bg'));
.selected {
  color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="names">
    <li class="name selected" data-bg="green">Name-1</li>
    <li class="name" data-bg="red">Name-2</li>
    <li class="name" data-bg="blue">Name-3</li>
</ul>

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

Having trouble with JQuery blur and enter key functionality not working properly

I'm currently utilizing the code below for inline editing. I am looking to trigger ajax when either the enter key is pressed or the user clicks away (blur). While everything works fine when the enter key is pressed, the AJAX call does not fire on bl ...

Rotate image in Vue3 using @click

I have a dashboard with a refresh button that I want to rotate 360 degrees every time it is clicked. How can I achieve this rotation effect on the image with each click of the refresh button? Below is the code snippet I have been working on, but it only r ...

Unlock the power of automatic code reloading in Rails with these simple steps

Looking for a way to implement 'hot code reloading' in a development Rails application? Let's say you're working on a Rails project and make changes to a stylesheet. Currently, you have to refresh the page using cmd-r or by clicking th ...

What's the reason behind the malfunction of this code on Chrome?

After recently installing Mobiscroll, I have been using the date scroller feature with the following code to manage the textbox. <script type="text/javascript"> $(function() { // create a datepicker with default settings $("#begi ...

Shuffle various div elements in a random pattern using jQuery

Check out this jQuery fiddle I'm using for my project: http://jsfiddle.net/BREvn/5/ Currently, I am creating a bird shooting game where the number of birds increases with each level. These birds are essentially represented by div elements, but I am ...

Using jQuery FancyBox in combination with Ajax

I have searched through numerous websites and many pages on Stackoverflow, but I have not found a solution to my problem yet. Basically, I have a hyperlink and I am trying to fetch an image from a database using an Ajax call and then display it in a FancyB ...

Use the Window.print function to easily print a HTML page to the printer

I've been attempting to achieve this for a while now. I have an HTML page with various icons, and when I click print, my goal is to have the page printed with all the icons intact. I followed the advice from a solution referenced in Printing specific ...

When adding multiple forms to a table, only the final form submission is successfully inserted

I have 2 forms on my website. The first form is static (general information). For the second form (project information), users can duplicate it using jQuery if they want to insert multiple projects. However, I am facing an issue where only the last project ...

What's wrong with this jQuery plugin, it should be so simple?

It seems like I'm missing a basic understanding here and I may need a cardboard cutout partner to help me out. Despite adding a new method to jQuery, as shown in the firebug command-line experience below, it just doesn't seem to work because the ...

Is it possible for the vertical borders of <span> to overlap?

When nesting multiple spans within each other and giving them borders, their horizontal borders overlap by default while their vertical borders stack. Check out a live example on JsFiddle: https://jsfiddle.net/4un9tnxy/ .html: <span><span>a& ...

What is the best way to transform the HTML retrieved from an AJAX GET request into an object using JQuery?

$.ajax({ method:"get", url:"/wall", data:"ajax=1", beforeSend:function(){}, success:function(html){ $("#grid_mason").append(html); //Inserting additional co ...

Difficulty parsing data from a JSON file using JavaScript

My knowledge about AJAX and JSON is very limited. I am currently attempting to import the information from dealerData.json into my MVVM viewModel, however, 'data' keeps returning as undefined. $(function () { var object; $.ajax({ ...

Guide to Enforcing Mandatory Input on Text Fields within JQuery Modal Box

I am facing an issue with validation in a JQuery Popup that contains text boxes. While the Required validation on the text boxes from the Model works fine outside the popup, it does not seem to work within the popup. I need assistance with understanding if ...

The overflow phenomenon similar to what can be found in Photoshop

I'm curious if there's a way to create an overlay effect similar to what you see in Photoshop or Illustrator. I have a background picture and a colored div in front of it. I'd like to add an overlay effect to the front div that looks more i ...

I'm puzzled as to why my fixed element is gravitating towards the right side of the entire screen instead of aligning with the right side of its parent element

I have inserted a code snippet that highlights my issue. I am attempting to ensure that the .navigation element remains fixed at the top of the colored divs, however, when using 'right: 0;', the .navigation element seems to shift to the right sid ...

Discovering the best way to organize and sort information retrieved from the backend within an Angular

How can I restrict a user to only search for data that has been provided from the backend and prevent them from creating new data? In my backend, there are two words: "Chart" and "Map". I am looking for a way to limit the user's search to only these ...

Best practice is to include the script on a page that is being loaded through ajax

I currently have a webpage named index.php. This page contains a form that takes input numbers and uses ajax to process the form, displaying the result on the same page. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> ...

Getting Ajax response in HTML Unit can be achieved by leveraging its capability to render the HTML content of the web page

My web application responds with JSON data when I make AJAX requests to the server for CRUD operations. This is because I utilize jQuery to handle the data without needing to refresh the page (MVC). When a new entry is created in the system, the server sen ...

Spring is experiencing an issue with the button functionality

When working with JSP files and JavaScript <c:set var="like" value="${like}"/> <c:set var="unlike" value="${unlike}"/> <script src="resources/js/jquery-1.9.0.js" type="text/javascript"></script> <script type="text/javascript"> ...

Having trouble with my navbar toggler arrow malfunctioning

I have developed a toggler button with an arrow icon that transforms into bars when clicked. However, I am experiencing some issues with the code: 1.) After clicking the toggler for the first time, the arrow icons change to bars successfully. But when I c ...