Ensure an item remains highlighted after being clicked on

Here is the code snippet I am currently working with:

$("li span").click(function() {
   $("li span").each(function() {
          $(this).css("background-color", "transparent");
   });
  $(this).css("background-color", "#ff3300");
});
.highlight {
  background: green;
}
span {
  display: block;
}
     
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div class="left-menu-inner scroll-pane">
  <ul class="left-menu-list left-menu-list-root list-unstyled">
      <li class="left-menu-list-active">
          <div class="left-menu-link">
          <a href="dashboard">
            <i class="left-menu-link-icon icmn-home2"><!-- --></i>
            <span class="menu-top-hidden">Dashboard</span>
          </a>
      </li>
    </ul>
</div>

Additionally, I have also tried another code snippet which is as follows:

<script>
// Add active class to the current button (highlight it)
var header = document.getElementById("myDIV");
var btns = header.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
 btns[i].addEventListener("click", function() {
   var current = document.getElementsByClassName("active");
   current[0].className = current[0].className.replace(" active", "");
   this.className += " active";
 });
}
</script>

However, both of the codes are only applying highlighting on mouseover and not maintaining the highlight when clicked.

Answer №1

When using the 'a' tag, clicking on it will take you to the URL specified in the 'href' attribute. However, you can achieve the same by changing the URL to '#' as shown in the example below. You can also replace the 'a' tag with other tags like 'p'.

`<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div class="left-menu-inner scroll-pane">
  <ul class="left-menu-list left-menu-list-root list-unstyled">
      <li class="left-menu-list-active">
          <div class="left-menu-link">
          <a href="#">
            <i class="left-menu-link-icon icmn-home2"><!-- --></i>
            <span class="menu-top-hidden">Dashboard</span>
          </a>
      </li>
    </ul>
</div>`

Check out the Demo here

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

Utilizing JavaScript or jQuery to adjust the cursor pointer value based on user input

Issue: Need help with live updating of input value to range input pointer [Check out my CodePen for reference][1] Adjust upper range input pointer based on lower range input pointer ][2] I am currently working on a range-to-range calculator for a book ...

Workaround for Google Chrome Session Cookie Functionality

After discovering that Chrome's "Continue where I left Off" feature allows cookies and sessionStorage to persist between browser restarts, it became clear that many users were facing the same issue. Despite numerous threads on sites like Stackoverflow ...

How about utilizing node.js as a peer for WebRTC?

Are there any available modules for utilizing node.js as a peer in WebRTC? I am interested in using WebRTC in a client/server manner rather than P2P for its ability to send packets unreliably (i.e. avoiding the delay caused by TCP's guarantee of packe ...

Ways to send information from a child component to its parent component when a button is clicked in the

Being new to Angular, I am faced with a challenge of organizing a large form into smaller modular components. I have created multiple child components and integrated their selectors in the main parent component. In the parent component, there is a 'sa ...

Refresh your HTML by reloading the JavaScript source

In my Ubuntu setup, I've been using chart.js to generate a graph displaying the values from a pressure sensor on an HTML document. Most of the project is complete, but I've encountered a challenge for which I haven't found a satisfactory sol ...

The delete function is not functioning properly after clicking "add to cart," but it works perfectly once the page is

I am encountering an issue with my shopping cart page. When I click on the "add to cart" button, the page refreshes before allowing me to delete an item from the cart. However, if I reload the page after adding an item to the cart, the delete function work ...

Angular6 - accessing elements that are not visible on the page

Currently, I am facing a situation where I have a component embedded in my HTML template that needs to remain hidden until a certain condition is met by checking a box. The tricky part is that the condition for setting "showControl" to true relies on calli ...

Switching the background color of a <td> based on an array provided in the AJAX response

My goal is to dynamically change the background-color of elements based on values in an array. However, I am facing a problem where all elements are displaying with the same color instead of changing according to the value. I have attempted using jQuery w ...

Switch Button Color in React Upon Adding to Favorites

Currently, I am facing a challenge with displaying a list of items and allowing users to add items to their Favorites. The problem lies in the fact that I am only capturing one favorite state. As a result, when a user clicks on one button, all item button ...

Exploring the paths with node.js variable walking

Currently facing an issue with the npm package "walk". The problem lies in the fact that it requires a string to define the path, which poses difficulty as the path varies based on the directory to be searched. var walkers = walk.walk(""+animeDir+"", opti ...

What is the best way to make my submit button display a message according to my switch statements in JavaScript?

function displayMessage() { var message; var firstName= alert( switch(firstName) { case "Cherry": message="Thank You Cherry!! Your order should arrive 20 days from February 4, 2017"; break; case "Micheal": ...

Utilize JavaScript Datepicker within the RStudio Environment

Can anyone help me figure out how to add a javascript datepicker to my Shiny app? I'm not sure how to import and execute the code in R. Here is where I found the source code: http://jqueryui.com/datepicker/ I'd prefer to integrate this code into ...

Can CKEditor be integrated with Mutation Observer? If so, how can this be achieved?

Trying to detect changes in the current CKEditor content. The goal is to identify which element's content has been modified when a user writes multiple paragraphs. Not well-versed in JavaScript or jQuery, but managed to come up with this code after s ...

Upon clicking the "show more information" button on the page, JavaScript executes the function to display additional details

<a href="#" class="button">Read More</a><br> I'm currently struggling with programming a button on my website. Specifically, I need the Read More button to display all information related to the CDs I have for sale when clicked. A ...

Accessing the internal undo and redo feature of a textarea input

Regular text areas and editable iframes come with a built-in undo/redo feature. However, when inserting certain content, this action cannot be undone because it does not register in the undo buffer. Is there a method to add custom states to the undo/redo ...

Stop Carousel when hovering over individual items (Owl Beta 2)

After creating a unique navigation that is separate from the carousel, I encountered some issues with the autoplay feature. Below is the HTML markup: <div class="carousel"> <div class=""> <img src="assets/img/carousel1.jpg" /&g ...

Discover identical values within an array of objects and consolidate certain duplicate keys and values

I have two lists of items list1 = [ { "id_0":356, "name":"India", "key1":150 }, { "id_0":356, "name":"India", "key2":200 }, { "id_0":748, "name":"Swaziland", "key1":140 }, { "id_0":748, "name":"Swaziland", "key2":180 } ] I ...

Customizing next.js _error page with i18n localization

Looking to create a customized error page for my Next.js project. I've been using the getServerSideProps method to localize my other pages, but I'm running into issues with translating strings on the _error page. I attempted to use the getStaticP ...

Ways to make text within a container smoothly slide down

Hello, I have a question about jQuery as I am relatively new to it. I am currently working on creating a team members section where clicking on a team member will slide down information about that person underneath. I have managed to set up the parent co ...

Change the styling of a div based on the hover state of another overlapping div

I have a list that can be sorted in the following manner: <html> <head> <title>jQuery UI Sortable - Example</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" inte ...