What is the best way to toggle the class "Active" when clicking on an li element, while removing it from the other elements simultaneously?

I am currently working on creating a dynamic menu where I need to alter the CSS of an li element when it is clicked, while keeping the CSS of the other li elements unchanged.

Here is my menu structure:

    <ul id="menu">
    <li><a href="#">Parent 1</a> </li>
    <li><a href="#">item 1</a></li>
    <li><a href="#">non-link item</a></li>
    <li><a href="#">Parent 2</a> </li>
</ul>

Here is the jQuery code I am using to apply CSS to the clicked element:

 $("#menu li a").click(function() {
    $(this).parent().addClass('selected');

    });

However, I am currently facing an issue where I am unable to remove the added CSS from elements that are not selected. Is there a solution to this problem?

Answer №1

Give this a shot

$("#menu li a").on("click", function() {
    $(this).parent().addClass('active').siblings().removeClass('active');
});

Live Demo

Answer №2

Give this a shot

$("#menu li a").click(function() {
  $("#menu li").removeClass('active');
    $(this).parent().addClass('active');
});

See it in action

Answer №3

Give this a shot, it's a foolproof method

$("#menu li a").on('click', function(e){
    $("#menu .active").removeClass('active');
    $(this).parent().addClass('active'); 
    e.preventDefault();
});

Answer №4

If you want to focus on the .siblings() method

$("#menu li a").click(function() {
    $(this).parent().addClass('active').siblings().removeClass('active');
});

Answer №5

For a more simplistic approach without Javascript, consider using radio buttons instead:

Utilize the sibling selector to apply styles to them

input[type='radio']:checked + label

DEMO

Answer №6

$("#menu li a").click(function(){
    // Check if the clicked item does not already have the active class
    if(!($(this).closest("li").hasClass("active"))){
        // Remove the selected class from any li elements with the active class within #menu
        $(this).closest("#menu").find("li.active").removeClass('selected');
    }
    // Add the selected class to the clicked li element
    $(this).closest("li").addClass('selected');
});

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

The most recent update of Blink does not support the complex selector :nth-child(2):nth-last-child(2){}

There is an unusual issue: after a recent update, the selector .groups .group:nth-child(2):nth-last-child(2){} suddenly stopped working. However, it still works perfectly in Webkit and Gecko browsers. Any thoughts on how to resolve this? Snippet of HTML ...

Is it appropriate to refer to a single page application as a web 3.0 application?

As time progresses, we are witnessing the rise of more and more single page applications or frameworks such as new twitter and Sammy. It appears to be a significant advancement where we move away from generating code on the server side, with servers actin ...

Is there a way to adjust the width of my web layout without sacrificing its responsiveness?

Struggling with my website layout design as I encountered an issue. The overall width of the layout is too excessive, and I want to introduce some margins on the sides for a better visual appeal. Although the responsive design works well originally, adding ...

Transform an array containing objects into a single object

Currently exploring the Mapael Jquery plugin, which requires an object to draw map elements. In my PHP code, I am returning a JSON-encoded array of objects: [ { "Aveiro": { "latitude": 40.6443, "longitude": -8.6455, ...

Issue with jQuery AJAX request not working as expected

I'm currently utilizing Rapid API to store my users' emails and passwords. Upon clicking, my send function should trigger, however, it seems that the program is not progressing through the AJAX call. I'm at a loss on how to proceed. Any ass ...

Tips for maintaining an open side menu

I'm having trouble keeping the side menu open when a user clicks on one of the child menu items. Ideally, I want section 1 to display section 2 content when hovered over, and keep both sections open even when section 2 is clicked. The only time they s ...

Retrieve data quickly and navigate directly to specified div element on page

I am facing an issue with scrolling on my website. While it currently works fine, I would like to make the scrolling instant without any animation. I want the page to refresh and remain in the same position as before, without automatically scrolling to a s ...

Grid element not displaying properly as intended

I'm having trouble centering the content of item in the middle column, it just won't budge. .home-grid-container { display: grid; grid-template-columns: auto; grid-template-rows: 0.10fr 0.98fr auto; height: 100vh; } .home-header { g ...

What is the best way to emphasize a table row during a search rather than just the text?

I am currently using a jQuery script that searches for a specific string in a simple text input field and highlights only the string itself if it is found. However, my data is organized within a table and I am interested in knowing if it is possible to hig ...

Django DRF functions properly, however it returns an error when sending a response to an AJAX request

Successfully implemented an AJAX request using PUT in DRF. All functionalities are functioning correctly except for the error callback being triggered: DRF section: class ProductDataViewSet(viewsets.ViewSet): authentication_classes = [SessionAuthentic ...

Is there a way to verify if td:nth-child(3) meets or surpasses a certain percentage threshold?

Currently in the process of developing a web page that retrieves various data sets, including three separate tables. My goal is to examine whether the value within the 3rd td element in each TR is equal to or exceeds a certain percentage. How can I determ ...

Assistance required for locating elements in Selenium using Css Selector

Hi there, I'm not really a developer. I've got two checkboxes in my table without any IDs. Usually, I can easily work with Selenium when elements have IDs, but in this case, the table was generated using jquery datatables and no automatic ID ass ...

Picture hidden beyond the words

I am trying to achieve a layout where an image is displayed behind an H1 tag, with the width of the image matching the width of the text. Here is my code: <div style="display: inline;"> <img src="http://img585.imageshack.us/img585/3989/m744. ...

Tips for ensuring all images are the same size within a div element

https://i.stack.imgur.com/EkmWq.jpg Is there a way to make sure all the images fit perfectly inside their respective border boxes without appearing stretched? I've tried setting fixed height and width within a div, but they always end up looking off. ...

Jssor Slider: Captions briefly overlap just as the slideshow begins to play

I am currently working on a slideshow with 3 caption-only slides. Here is the code snippet: <div id="sliderHeader_container" style="position: relative; width: 965px; height: 85px;"> <!-- Slides Container --> <div u="slides" style=" ...

approach for sending an array to model-view-controller through ajax in asp.net

How can I pass an array in MVC to store data in SQL Server? I am trying to save the score of each question using Ajax and jQuery, but it only saves one piece of data from the list array. The array variable is result that needs to be assigned to eachscore. ...

What is the best way to add Vue dependency using CDN?

For my project which is built using Kendo, Vue, .Net, Angular and jQuery, I need to incorporate https://www.npmjs.com/package/vue2-daterange-picker. <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-c ...

Which method proves to be quicker: storing data on a DOM element with a class attribute, or using jQuery data?

In my application, I have a render loop that constantly updates the appearance of several DOM elements based on data fetched from an external source. Each element needs to have presentational classes applied according to this data. For example: var anima ...

Why does the pound symbol in z-index always show up in Angular?

Having an issue with my code where I set a z-index in the CSS like this: .mat-mini-fab { position: absolute; right: 5px; top: 4px; z-index: 999; box-shadow: none !important; } However, whenever I visit my site, the z-index is not being appl ...

Could the conflicting interaction between CSS transformation and animation be resolved by adjusting the order of the HTML elements

Hey there! I'm facing an interesting challenge with my menu design. The menu has rounded ends and diagonal spaces created using CSS transform skewx. Additionally, I have an animated element on the page. The issue arises when the animated element is p ...