Update the background color of an li element upon clicking

Is there a way to change the background color upon clicking on the li anchors?

<div class="text-center row">
  <ul  class="col-md-12 secondNav">
    <li class="navbar-brand nav-item" style="margin-right: 9%">
      <a href="#" ><strong>HOME</strong> </a>
    </li>
    <li  class="navbar-brand nav-item" >
      <a href="#"><strong>COMPARE</strong></a>
    </li>
  </ul>
</div>

Answer №1

To modify the background color of an li element, you can utilize jQuery. Below is an example code snippet:

$(document).ready(function(){
  $('.nav-item').click(function(e){
    $(e.target).css('backgroundColor', 'red');
  });
});

Check out this JSFiddle link for a live demo.

Answer №2

While I don't typically recommend this approach, it is indeed feasible to achieve this without the use of JavaScript! Take a look at the following example: https://jsfiddle.net/age5zdkb/3/

<div class="text-center row">
  <ul  class="col-md-12 secondNav">
    <a href="#" >
      <li class="navbar-brand nav-item" style="margin-right: 9%">
        <input type="checkbox" id="demo"/>
        <label for="demo"><strong>HOME</strong></label>
      </li>
    </a>
    <a href="#" >
      <li  class="navbar-brand nav-item" >
        <input type="checkbox" id="demo1"/>
        <label for="demo1"><strong>COMPARE</strong></label>
      </li>
    </a>
  </ul>
</div>

label {
    display: block;
}

input[type="checkbox"] {
  display:none;
}

#demo:checked + label, #demo1:checked + label {
    background: pink;
    color: white;
}

Answer №3

Here is a way to achieve this without relying on any external libraries.

const listItems = document.querySelectorAll('.navbar-brand');

listItems.forEach(li => {
  li.addEventListener('click', () => {
    li.classList.toggle('alt-background');
  });
});
.alt-background {
  background-color: lightgray;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class="text-center row">
  <ul  class="col-md-12 secondNav">
    <li class="navbar-brand nav-item" style="margin-right: 9%">
      <a href="#" ><strong>HOME</strong> </a>
    </li>
    <li  class="navbar-brand nav-item" >
      <a href="#"><strong>COMPARE</strong></a>
    </li>
  </ul>
</div>

View the code in action on jsFiddle

Answer №4

If you want to dynamically add an active class using jQuery when a nav-item is clicked, you can achieve this by applying background color for the active item in CSS.

https:/ /example.com/

In JavaScript

   $(document).ready(function(){
            $('.nav-item').click(function(e){
                $('.secondNav .nav-item').removeClass('active');
                $(this).addClass('active');
             });
    });



In Cascading Style Sheets (CSS)
.secondNav .nav-item.active {
  background-color: blue;
}

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

Creating a sophisticated form design with multiple input fields using DIV elements in HTML

I am looking to create a multi-column form layout that allows each row to have a different number of fields. My initial approach was using tables and the colspan attribute within td tags for layout structure. However, I have learned that using tables for l ...

Adjusting Media Queries according to the browser window's zoom level

Is there a way to detect the browser width dynamically? For instance, can I adjust the CSS styling based on zoom adjustments like ctrl + or ctrl -? By "box," I am referring to a perfectly square shape. So, when the browser width is 100%, I want a layout wi ...

IE z-index bug affecting Youtube videos

I've been experimenting with the YouTube API and I've included the following code snippet in http://jsfiddle.net/aaronk85/wapFR/. <div id="video-wrap2"></div> <div id="video-wrap"> <div id="play-video"></div> &l ...

What is the best method for eliminating a character from all elements in jQuery classes?

I am working on an Angular 4 app where every .inner-page class in a html element includes a "/". For instance: <div _ngcontent-c0="" class="inner-page /login"> <div _ngcontent-c0="" class="inner-page /register"> I need to eliminate the "/" c ...

Can you place 4 table cells in the first row and 3 table cells in the second row?

Exploring the world of HTML and CSS designs for the first time. Here's a code snippet I've been working on: <html> <body> <table width="100%"> <tr> <td width="25%">&#160;</td> ...

Issue with Bootstrap 4 Carousel Indicators Not Updating Active State Properly

I set up a Bootstrap Carousel and intentionally left the carousel-indicators section blank so that it could be dynamically populated with jQuery based on the number of slides. <section class="carousel-banner side-by-side darkblue-background-color&q ...

Curved edges, Layering, Content overflow restriction

My design consists of two circular divs with the border-radius property set to its max value. The first circle contains a header div with a unique background-color and overflow:hidden to create the illusion that the top portion of the circle has a differen ...

Steps for implementing remote modals in Bootstrap 5 using CS HTML

I'm attempting to implement a remote modal window in Bootstrap 5 with C# MVC. The endpoint for the modal partial view is configured correctly. According to this discussion on Github, all that needs to be done is to call some JavaScript. However, it ...

What could be causing me to receive null when trying to retrieve an element with document.getElementById, even after invoking $(document).ready(function() { ... })?

Here's a small example. I'm feeling a bit rusty with JavaScript, as it's been some time since I last worked with it. The problem I'm encountering is an error in Chrome developer tools: "Uncaught TypeError: Cannot set property 'src ...

The CSS overflow property is a great tool to demonstrate how a box can be neatly cut off at its

According to the specifications outlined in this resource, In situations where overflow occurs, the 'overflow' property determines if a box is clipped to its padding edge. Additionally, it specifies whether or not a scrolling mechanism will b ...

Present XML data on an HTML page to generate interactive form features

I have an application that features a checkbox tree. I would like to automatically pre-select those checkboxes if the user had previously checked them. To achieve this, I receive XML data from my backend Perl script which contains information on which che ...

The content at the center of the page is shifting to the right side when the browser is resized

I am currently working on creating a random quote generator at the following link: http://codepen.io/Kestvir/pen/peqjZZ. During the html/css aspect of the project, I have run into an issue with the content inside a transparent background. Whenever I resi ...

Unfold an HTML element and reveal a sneak peek of its content with the aid of JQuery

I need a way to organize and display a set of 5 lines of text vertically. Specifically, I want them arranged like this: 1) Line one 2) Line two 3) Line three 4) Line four 5) Line five However, I have a special requirement where only the first ...

Implementing dynamic CSS switching for right-to-left (RTL) support in a multilingual Next.js application

As I work on my multilanguage application with Next.js, I'm encountering a challenge in dynamically importing the RTL CSS file for Arabic language support. My aim is to seamlessly switch between RTL and LTR layouts based on the selected language. M ...

Issue encountered while incorporating a PHP file into Javascript code

I'm facing a particular issue where I have a PHP file that is supposed to provide me with a JSON object for display in my HTML file. Everything seems to be working fine as I am receiving an output that resembles a JSON object. Here's the PHP file ...

What are the steps to customize the appearance of a ComboBox using CSS?

I'm struggling to style the items in a combo box when it's dropped down. Currently using vaadin-time-picker on Svelte, but my issue persists due to the combo box included. Despite experimenting with CSS, I haven't had any success. My goal i ...

Model is disregarding media queries

Using LESS for CSS compilation, I have encountered an issue with the media query in my code. Specifically, I am attempting to apply different styles for mobile devices but they are not being rendered as expected. #main-wrap header #hdr-nav nav { width: ...

Guide on obtaining an obscure style guideline in MS Edge using JavaScript

If you are looking to utilize the object-fit CSS rule, keep in mind that it is not supported in MSIE and MS Edge Browsers. While there are polyfills available for IE, none of them seem to work in Edge from my experience. For instance, the polyfill fitie b ...

Troubleshooting problem with ion-input in Ionic 3 regarding the keyboard issue

Issue with Keyboard Overlaying Button In my ionic3 app, I am facing an issue where the keyboard overlaps the "Registrarse" button when it is open, as shown in the image. The button is positioned at the bottom of the ion-content using CSS rules such as pos ...

Trigger the activation of an input field upon clicking an image labeled "edit"

I am currently developing a website where administrators have access to a dashboard page that displays a list of users. I am looking to implement a feature that allows admins to change the roles of other users directly from the same table row. Below is th ...