The art of precise JQuery selection

I have a menu that changes dynamically. I want to be able to highlight the clicked item in the menu when someone clicks on it.

$("#my_menu > li").click(function(){
   var clickedId = $(this).attr('id');
   $("#" + clickedId).css("font-weight", "bold");
   $("#" + clickedId).css("background-color", "#E0E0E0");
   $('#navigation_submenu').show(); //this is not important
});

However, I also need to revert the other menus back to their initial state once one has been clicked. Can anyone help me with this? Thank you!

Answer №1

To achieve this, it is recommended to use the addClass() and removeClass() functions like so:

  • Start by creating a CSS class for the active items:

    .active {
       font-weight:bold;
       background-color:#E0E0E0;
    }
    
  • Next, implement the following JQuery code:

    $("#my_menu > li").click(function(){
       //Remove current active item
       $("#my_menu > li").removeClass('active');
       //Add 'active' class to the clicked element
       $(this).addClass('active')   
    });
    

For a live demonstration, you can view this Demo Fiddle

Answer №2

Is it something like this example?

Styling with CSS

li.active
{
    font-weight: bold;
    background-color: #E0E0E0;
}

Adding functionality with JavaScript

$("#my_menu > li").on("click", function()
{
    $("#my_menu > li").removeClass("active");
    $(this).addClass("active");
});

Answer №3

Try using a CSS class named "selected" instead.

$('.selected').removeClass('selected');
$(this).addClass('selected');

Don't forget to define your CSS class with the desired styling.

Update: Oops, it looks like others have already provided a similar solution.

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

Using Jquery to append a selector to an object that has already been selected

Hey there, When utilizing the standard selector, I've managed to choose the grandparent of an input text field (which is essentially a <td> element), and then used .next() function to pick the next row. var nextOne = $(this).parent().parent(). ...

The absence of underlines for <a href> and <u> is causing an issue

Below is a snippet of code that I am working with: echo "<form> <div id=\"error\"align=\"center\">"; echo "You've either entered the incorrect <b>username</b> or incorrect <b>passwor ...

Displaying a list of terms and their corresponding definitions side by side

I need to display multiple rows of data, with a title and corresponding data on the same line. While I have found answers on sites like SO (e.g. How to style dt and dd so they are on the same line?), the suggested solutions don't seem to work for my s ...

Mastering the Art of Absolute Positioning in HTML Tables' Header Row

I have a table with 80 rows. How can I make the first row fixed? I attempted to add position: fixed; to the but unfortunately, it didn't work. Is there a way to achieve this using CSS or jQuery? <table> <thead> <tr> <td sty ...

The functionality of Jquery is successfully integrated into a specific function, however it seems to only work for one of the calls. To make the other call work,

After a user makes a selection, I am attempting to reset the 'selected' item. This process calls the Vue function tS() shown below. The issue lies with the first call $('#sel1').prop('selectedIndex',0);, as it only seems to wo ...

What could be causing ngInfiniteScroll to not work properly with tables?

I've been attempting to incorporate ngInfiniteScroll into my table using ng-repeat on <tbody> however, it isn't triggering when I reach the end of the page. <div infinite-scroll="list.getMoreItems()"> <table md-table md-row-se ...

The issue persists with multiple instances of Swiper js when trying to use append and prepend functions

I'm encountering an issue with my swiper carousels on the page. Despite everything working correctly, I am facing problems with the append and prepend slide functions. When I remove this part of the code, everything functions as expected. $('.s ...

Strategies for integrating a username-only login using Firebase without requiring a password or email address

For my class assignment, I'm developing a webapp and want to implement a login system with only a username. However, when I try sending just the username to the database, it gets stored as a child under the connection ID in Firebase. Below is the Java ...

activated by selecting a radio button, with a bootstrap dropdown menu

I'm having trouble triggering the dropdown in Bootstrap by clicking on a radio button. It seems like a simple task, but I've been struggling with it all day. According to Bootstrap documentation, you can activate the dropdown using a hyperlink o ...

Incorporate characteristics into a text box using jQuery

Currently, I am working with asp.net MVC. There is a control that looks like this: <%= Html.TextBox("username") %> I would like to add a lost focus event to this control. This is what I have tried: $(document).ready(function() { $("#username") ...

Having trouble adjusting the vertical position of jQuery Spinner buttons

I'm attempting to customize the jQuery spinner with styling applied like this: <span class="ui-spinner ui-widget ui-widget-content ui-corner-all" style="height: 14px;"> <input id="testSpinner" class="ui-spinner-input" name="value" aria-value ...

Alter the color of the text when hovering over it, only in the area where the

Is there a way to change the color of text only where the mouse is placed, without affecting the entire text? Similar to this example https://i.sstatic.net/vdYEn.png I'm looking to have a circle follow the mouse, and when hovering over text, only th ...

Adding and removing classes in NativeScript: A step-by-step guide

Attempting to lower the opacity of my StackLayout while making an Ajax API call. The structure of my page is as follows: <Page loaded="pageLoaded" class="page" xmlns="http://www.nativescript.org/tns.xsd"> <ActionBar title="Settings" clas ...

Tips for adjusting image size to take up only half of the screen in NextJS

Struggling to resize an image to fit only 50% of the screen in NextJS? The Image component provided by NextJS comes with its own inline styling, making it tricky to customize. Currently, I attempt to style the image by wrapping the Image component in a spa ...

What is the best way to ensure that the sidebar appears after the content on mobile devices, even when there are full-width blocks within

I attempted to enclose fixed-width content and sidebar within a common container, but when it came to mobile devices, I could only come up with a solution where the sidebar is positioned after the content and before the full-width content. However, this ar ...

Assigning an alternating class to each consecutive chat message, while ensuring that all messages share the same class

I currently have a basic node JS chat application set up. It utilizes express, mongodb, socket.io, and jQuery for the frontend. While everything is functional, I am looking to style every other message with a different color and alignment in the chat. Be ...

Element imitating the edge of the screen extending to the edge of the container

Looking to customize a website design (utilizing bootstrap 4) with a gradient line that starts from the title and stretches all the way to the left edge of the container. While I have managed to set this up, the full gradient effect is not visible. To addr ...

Display a button that allows the header to slide down after sliding

Currently building my website and encountering an issue. At the top of the page is my header with a navigation menu inside it. As I scroll down the page and the header moves out of view, I would like another DIV to slide down from the top (fixed in positi ...

Alignment of Bootstrap thumbnails in a horizontal layout

After adding the thumbnail class to my thumbnails div, I noticed that some of the thumbnails were smaller in size than others. Wanting them all to have the same height, I decided to give each thumbnail a fixed height of 210px. However, this caused the sm ...

Peruse the written content and implement it within a div element

If any of the words match, I want to highlight them in a different color on the website for the user to see. var main = document.getElementById("selectedItem").innerText; var opinionTargets = ["screen", "cover", "size", "waterproof", "voice", "light", "pr ...