What is the best way to eliminate the background color from one span after selecting a different one?

I created a span element that changes its background color when clicked, but I want the background color to switch to the newly clicked span while removing it from the previously clicked one. Can someone help me achieve this?

CSS

                list-style: none;
                font-size: 14px;
                padding: 7px 0px 7px 23px;
            }

            ul li a {
                color: #676a74;
                text-decoration: none;
            }

            ul li a span {
                float: left;
                width: 11px;
                height: 11px;
                margin-left: -13px;
                margin-right: 5px;
                top: 4px;
                border: 1px solid #d1d3d7;
                position: relative;
                transition: all 0.5s ease-in-out;
            }

            ul li a span.active {
                background: green;
            } 

HTML

            <li>
                <a href=""><span class="list"></span>Electronics</a>
            </li>
            <li>
                <a href=""><span class="list"></span>Clothes</a>
            </li>
            <li>
                <a href=""><span class="list"></span>Home & Office</a>
            </li>
        </ul>

JQUERY

            e.preventDefault(); $(this).parent().find(".list").addClass("active").siblings().removeClass("active");
        });

Answer №1

Hopefully this solves the problem

$(".list").removeClass("active");
$(this).addClass("active");

Answer №2

When a tag is clicked, the active class is removed from all list classes. Then, the active class is added to the span element that is a child of the clicked tag.

$('a').click(function(){
$(".list").removeClass("active");
$(this).children('.list').addClass('active');
})
ul{
   list-style:outside none none;
}
ul li a {
                color: #676a74;
                text-decoration: none;
            }
ul li a span {
                float: left;
                width: 11px;
                height: 11px;
                margin-left: -13px;
                margin-right: 5px;
                top: 4px;
                border: 1px solid #d1d3d7;
                position: relative;
                transition: all 0.5s ease-in-out;
            }

            ul li a span.active {
                background: green;
            } 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
    <li>
        <a href="javascript:void(0)"><span class="list"></span>Electronics</a>
    </li>
    <li>
        <a href="javascript:void(0)"><span class="list"></span>Clothes</a>
    </li>
    <li>
        <a href="javascript:void(0)"><span class="list"></span>Home & Office</a>
    </li>
</ul>

To add the active class on span click

    $('.list').click(function(){
       $(".list").removeClass("active");
       $(this).addClass('active');
    })

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 choosing a block using Puppeteer

Trying to retrieve the height of a series of blocks using Puppeteer, I encountered an issue where I couldn't select my block in page.evaluate() due to an error. The code snippet in question is as follows: (async () => { const browser = aw ...

I am a beginner in JavaScript and I'm struggling to understand why it is not executing the else statement

As a newcomer to JavaScript, I have only learned from one website. Unsure if my code is outdated or contains elements of other software like jQuery, all I know is that it refuses to execute the else statement. <!Doctype html> <html> <body ...

Creating a navigation bar in React using react-scroll

Is anyone able to assist me with resolving the issue I am facing similar to what was discussed in React bootstrap navbar collapse not working? The problem is that although everything seems to be functioning properly, the navbar does not collapse when cli ...

Is there a way to simultaneously view and send this JSON data to the server using console.log?

I'm looking to inspect the JSON data being sent and received by the server, but I'm struggling to understand how promises work in this scenario. When I use console.log() on the function body, I see Promise { pending }. Unfortunately, I can' ...

Access a file from a specified route within Express

Recently, I created a custom Node module that requires a configuration file in CSV format. My goal is to implement this module within an Express Route module; however, I am encountering difficulties related to the loading of the configuration file. Should ...

responsive position absolute to the auto width of position absolute

Here is an example of my CSS code: https://jsfiddle.net/80e4u0dd/ When you hover over the orange box, the a element gets underlined. The orange box needs to stay above the "long text" in the green box, just like it is currently. The issue is that the oran ...

What is the process for activating focus on an input element within a mat-select component?

How can I activate the cursor on the HTML input element (search field) using a keyboard inside mat-select? It functions properly when using a mouse, but in order to meet WCAG requirements, it needs to be fully functional with keyboard navigation. Click h ...

Load pages using ajax with conditional if statements

I am currently developing a website that relies on ajax to load its inner pages. However, I need certain groups of pages to have background and container width changes as well. Is there a way for me to use conditional if statements to modify the class or ...

Leveraging Nextjs Link alongside MUI Link or MUI Button within a different functional component (varieties)

Currently in my development setup, I am utilizing Next.js (10.2) and Material-UI (MUI) with Typescript. In the process, I have implemented a custom Link component: Link.tsx (/components) [...] On top of that, I have created another iteration which functi ...

Converting a JS result set into JSON format

Having an issue with converting code from XML output to a JSON object instead. Here is the current code: public String evaluate() throws Exception { // Code block here } I need assistance in using GSON JSON utility methods to convert the result s ...

Troubleshooting a Problem with CSS Div Multi-column Formatting

I have designed a multi-column div that displays correctly in Firefox but has formatting issues in Chrome and IE. In Firefox, the three columns appear properly with the frame of the last item in column one ending correctly. However, in Chrome and IE, the f ...

Unable to find 'react/lib/merge' module

I'm currently working on a React project and utilizing Babel and Webpack. Within one of my files, I have this require statement: var merge = require('react/lib/merge'); Unfortunately, I'm encountering the following error: ERROR in . ...

Optimizing jQuery UI autocomplete choices through filtering

Currently utilizing the jqueryUI autocomplete feature on my website. Let's say I have the following entries in my database... apple ape abraham aardvark Upon typing "a" in the autocomplete widget, a list appears below the input field displaying the ...

Transform post-back into PHP using JSON for Ajax posting

Currently, I am facing a challenge in integrating a Codeigniter application into Wordpress using a plugin. The trouble arises when the control encounters an issue while confirming the data for a new appointment. VIEW <div id="wizard-frame- ...

Is there a way to enlarge images when hovered using canvas?

I came across a fascinating example at the following link: , where the images expand when hovered over. I am aware that this can be achieved using jquery, but I have concerns about its speed and reliability. I would like to experiment with d3.js, although ...

Why won't my AngularJS Google Maps marker trigger any events?

My issue is with the marker event not working on a UI Google Map. I am using this link. Here is my view setup: <ui-gmap-markers models="mapResult" fit="true" idkey="mapResult.id" coords="'form_geo'" click="'onclick'" events="mapRe ...

What could be the reason for the malfunctioning transition effect in my slider animation?

Having trouble getting my slider animation to work. I've tried different CSS styles but the slide transition is not functioning as expected. When one of the buttons is clicked, I want the slide to change from right to left or left to right. Can anyone ...

Discovering hidden files within appsettings.json in ASP.NET Core 6 using Program.cs

Within Appsettings.json, the code resembles the following: { "Project": { "ConnectionString": "Data Source=(local)\SQLSERVER; Database=MyCompany; Persist Security Info=false; User ID='sa'; Password='sa ...

What is the best method for choosing all options in a select box in IE without experiencing the scrolling effect?

Here's the scenario: I have a select element with multiple options and a checkbox that allows users to select/deselect all options. The issue arises in Internet Explorer, where selecting all options using code causes the entire select box to scroll un ...

Include money symbols within input fields with padding and vertical alignment

I am looking to create an input field that includes either € or $ currency symbols. The challenge is ensuring perfect vertical centering inside the input, especially when using padding. Is there a foolproof method to achieve this? https://i.stack.imgur ...