How to apply an active class using Javascript and jQuery

I've been trying to figure out how to apply the active class to my unordered list using jQuery. Despite attempting various solutions found on Stackoverflow, nothing seems to be working. My goal is to have the text color change to red when the active class is added. Can anyone shed some light on why this code isn't functioning as expected?

$("li").click(function() {
  $("li").removeClass("active");
  $(this).addClass("active");
});
.active { color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="navbar">
  <li class="active"><a href="#">link</a></li>
  <li class=""><a href="#">link</a></li>
  <li class=""><a href="#">link</a></li>
  <li class=""><a href="#">link</a></li>
  <li class=""><a href="#">link</a></li>
  <li class=""><a href="#">link</a></li>
</ul>

Additionally, I am encountering an error in my browser console:

 error: $("li").click() is not a valid function

Answer №1

Your code is functioning properly. However, it seems that you are encountering an error message

error: $("li").click(function() is not a valid function
. This error typically occurs when our custom JS code containing jQuery functions is loaded before the main jQuery script in the document.

To resolve this issue, ensure that the jQuery library code is placed within the HTML <head></head> tags

.active { color: red; }
.active a { color: red; }
<!doctype html>
<html>
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  </head>
  <body>
    <ul class="navbar">
      <li class="active"><a href="#">link</a></li>
      <li class=""><a href="#">link</a></li>
      <li class=""><a href="#">link</a></li>
      <li class=""><a href="#">link</a></li>
      <li class=""><a href="#">link</a></li>
      <li class=""><a href="#">link</a></li>
    </ul>

    <!-- Your custom script here -->
    <script>
      $("li").click(function() {
        $("li").removeClass("active");
        $(this).addClass("active");
      });
    </script>
  </body>
</html>

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

An Easy Breakdown of How AJAX Works

I have a question that I believe someone with knowledge of AJAX should be able to answer easily. However, despite searching online, I haven't found an explanation that fits what I am looking for. I'm currently working on a site without any prior ...

Tips for utilizing identical properties across numerous styled elements:

Utilizing the styled-components library, I have enhanced the header components from the Blueprintjs library. The current template for the H6 component appears as follows: export const DH6 = styled(H6)` color: ${(props) => (props.white ? "white&qu ...

Animate a list to expand and collapse the menu options

Here's the concept I'm aiming to achieve: When "PORTFOLIO" is clicked, smoothly push down everything on the page; New links should fade in smoothly; If "PORTFOLIO" is clicked again, reverse all animations. This is my current code snippet: $( ...

Collaboratively accessing a shared constant in two separate JavaScript files

I am diving into the world of JavaScript and Node.js. I am currently experimenting with Puppeteer to extract the text value of a tag and store it in a constant variable. However, I am encountering difficulties when trying to integrate this value into my ...

What are some ways to style a DropDownList?

I'm looking to style the dropdownlist to display two field columns similar to the image shown. Is it possible to achieve this using HTML5 datalist or jquery? ...

Arrangement of Columns in Bootstrap 4 - Three Columns Aligned Vertically on the Left, One on the Right

My goal is to achieve a Bootstrap 4 layout like the one shown in the image linked below: https://i.sstatic.net/gY6m5.png For large devices, I want the Search Form, CTAs, and Button ads to be arranged vertically in a column that spans 4 units, while the C ...

Autofill Dropdown in AngularJS Using Data from Previous Page

Despite searching extensively on StackOverFlow, I was unable to find the answer I needed. So, I am posting my question below. I have a form that includes a dropdown menu. When a user clicks a button, they are taken to a new HTML page with additional infor ...

What is the best way to apply ngClass to style a JSON object based on its length?

Currently, I am working with a mat-table that displays data from a JSON object. My goal is to filter out all records with an ID of length 5 and then style them using ngClass in my HTML template. How can I achieve this? Below is the code I am working with: ...

Emulating navigator.onLine in Node.js

I have recently started working on a Node.js application. To further my understanding of Node, I am developing a utility app for network detection purposes. Within this app, my primary objective is to determine: a) whether my computer is connected to the ...

Aligning a div in relation to the background image

I am seeking guidance on how to center a Div Box and make it responsive relative to the background image. The div box should be contained within the white box, similar to the example shown here: body{ font-family: 'Roboto Mono', monospace; ...

Unable to access a directive value within the controller

Attempting to create a table that can extract URL parameters from its grid-url directive. The plan is to then use this extracted URL in the controller with $http. However, it doesn't seem to be working as intended since the value always turns out to b ...

Sorting two different divisions is an example

I need advice on how to toggle between two divs, A and B, without having to reload the page. Ideally, I would like to have three buttons - one that shows only div A when clicked, another that displays only div B, and a third button that shows both A and ...

Creating multiple dynamic routes in Next.js based on specific IDs

Hey there! Currently tackling a challenge in my Nextjs project involving Events->Event->Schedule. My goal is to simply click on an event and be directed to the corresponding event details. Within the event, there should be a schedule that links to th ...

Determining a User's Connection Status in ReactJS: Cellular Network or WiFi?

Are there any tools or applications available that can determine if a user is connected to WiFi or using a cellular network? ...

Obtaining the selected value from multiple dropdown menus by clicking a button in Angular 6

Looking for help with getting the selected values from 2 dropdowns in Angular 6 or Typescript? Check out my code below and let me know if you can assist! app.component.html <select class="select1"> <option>country1</option> &l ...

Difficulty in adjusting the height of the popover menu that appears when using the Select Validator in Material UI

I am having trouble adjusting the height of a popover that emerges from a select validator form in Material UI. Despite attempting various methods, including adding the following CSS to the main class: '& .MuiPopover-paper': { height: &apos ...

iOS Devices experiencing issue with beforeunload event not triggering

When a user tries to leave the page without saving, I use the beforeunload function to display a popup warning them that their changes may not be saved if they proceed. They can then choose to leave or stay on the page. However, I am facing an issue with ...

Acquiring the ClientID from a user control embedded within the application

On one of my web pages, I have set up the following: <%@ Register Src="MyLocationControl.ascx" TagName="MyLocationControl" TagPrefix="uc3" %> Inside MyLocationControl.ascx, there is a textbox field that will contain hidden values such as name, addr ...

PHP not displaying value upon submission

Looking for a simple PHP code to post a value and echo it inside an if(isset()) statement when clicking on the submit button, but unfortunately, it's not functioning as expected. <?php if(isset($_GET['q'])) { $q=$_GET[&ap ...

Ways to change a CSS rule for a class when the data-attribute value aligns with an anchor tag's value?

Looking to incorporate read more links into various sections of a WordPress page, where clicking the link reveals content hidden with CSS. Here are a couple of sample sections in HTML format that I aim to replicate: Section 1: <p>Curious about what ...