Achieving class toggling between elements using event.target

I'm currently working on a JavaScript app project and I'm looking to add classes to my navigation links using the event.target property. I have two different functions that should toggle the class names between the two navigation links. For example, when the user clicks on the "home" link, I want to give it the .active class, and if they click on "home2", I want to remove the .active class from "home" and apply it to "home2". I am seeking a Vanilla JavaScript solution for this issue. Any ideas?

function goHome(event) {
    event.target.classList.add('active')
}

function goSomeWhere(event) {
    event.target.classList.add('active')
}
.active {
    color: red;
}
<div class="menu">
    <li onclick="goHome(event)" class="primary">home</li>
    <li onclick="goSomeWhere(event)" class="primary2">home2</li>
</div>

Answer №1

To start, you can remove the active class from any element that currently has it, and then add it to the one that the user just clicked on. Here's how you can achieve this:

const menu = document.getElementById('menu');

menu.addEventListener('click', (event) => {
    menu.querySelectorAll('.active')
        .forEach(link => link.classList.remove('active');

    event.target.classList.add('active');
});

If you give your div an id of menu, this code should work smoothly. However, I recommend changing the div to a nav tag since it represents navigation elements more accurately.

By following this method, you can eliminate the need for the onclick attribute in your list items.

Answer №2

Using inline event handlers is generally discouraged, as explained here.

We can implement event delegation to manage the active state efficiently. The handler utilizes Element.closest() method to identify the source of the click.

Note: I have updated the parent element from a div to a ul.

document.addEventListener(`click`, handle);

function handle(evt) {
  const li = evt.target.closest(`li`);
  const menu = evt.target.closest(`.menu`);

  if (li && menu) {
    return menu.querySelectorAll(`.primary`).forEach(el =>
      el === li 
      ? el.classList.add(`active`) 
      : el.classList.remove(`active`) );
  }
}
.active {
  color: red;
}

.primary {
  cursor: pointer;
}

.primary:hover {
  text-decoration: underline;
}

.primary:not(.active):hover {
  color: green;
}
<ul class="menu">
  <li class="primary">home</li>
  <li class="primary">home2</li>
</ul>

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

Error Encountered on Android Due to Sec-WebSocket-Key Mismatch

I'm facing an issue with my WebSocket implementation using PHP. It seems to work fine on my desktop computer, but when I try to access my website on an Android device, the server implementation throws an error during the handshake process. It shows ...

Adjustable scrollbar for varying content heights

Below is the HTML structure that I am working with: <div id="body"> <div id="head"> <p>Dynamic height without scrollbar</p> </div> <div id="content"> <p>Dynamic height with scrollbar< ...

Jade not binding correctly with Angular.ErrorMessage: Angular bindings are

Struggling with simple binding in Angular and Jade. I've tried moving JavaScript references to the end of the document based on advice from previous answers, but still no luck. Any ideas on what might be wrong? File: angular.jade extends layout blo ...

Searching for a specific string within an array of structured objects: a step-by-step guide

Consider the following scenario: let distinctValues = []; distinctValues.push("ValueA"); distinctValues.push("ValueB"); let firstValue = distinctValues[0]; let searchResults = []; let gridData = grid.jqGrid('getGridParam', 'data'); ...

Determining the positioning of a tablet with a JavaScript algorithm

We are currently working on developing an HTML5/JavaScript application specifically designed for tablet devices. Our main goal is to create different screen layouts for landscape and portrait orientations. Initially, we attempted to detect orientation cha ...

Unable to collapse the bootstrap navbar on a targeted screen size

My intention was to collapse the Bootstrap navbar when the screen width reaches 1280px. However, instead of collapsing, the navbar appears at the top. Here is the code snippet I am using: body { padding-top: 90px; ...

css readonly input textbox not changing background color when set

I've come across an old Classic ASP form that requires additional functionality, and I'm currently using IE11. To address this, I decided to include a doctype like so (even though I'm unsure of its necessity): <!DOCTYPE html> In my C ...

transferring a function from a main component to a nested component using swipeout functionality in react-native

I am attempting to transfer a function from a parent container to a child container within react native. The user is presented with a list of items on the screen, where they can swipe the list to reveal additional options. Child import React from &ap ...

The Ionic framework has a defined variable

In my code, I have initialized a variable inside the constructor like this: constructor(public http: HttpClient) { this.data = null; this.http.get(this.url).subscribe((datas: any) => { this.dbUrl = datas[0].db_url2; console.log(this ...

Attempting to create a button using JavaScript, however, encountering difficulties with functionality

I'm a beginner in JavaScript and I decided to use an app to help me learn the language. In my index.html file, I have included the following code: <div data-role="collapsible"> <h3>Reset Score</h3> <button type="button" id="r ...

sending an object between JavaScript and PHP and vice versa

This task seems quite challenging and not easily achievable. Imagine having a button inside a div in HTML. When you click the button, you call a PHP function using AJAX. The goal is to send the element that triggered the click event (or any other element ...

JavaScript function returning code

I am trying to create a JavaScript object with multiple functions, but I keep encountering an exception undefined is not a function Here is my JS code: var Cars = null; $(function () { Cars = function() { return { ...

The MUI Select component requires two clicks to open its menu if another Select component's menu is already open

I have been developing an application with two dropdowns (Select components) positioned next to each other, denoted as A and B. When A is open and the user intends to click on B to open it, I observed that in the default behavior of material UI, the user ...

Struggling with a Failed prop type error in React? Learn how to resolve the issue of an Invalid prop being

I am currently in the process of developing a small react application where users can register, login, and perform various other actions. With respect to the Login feature, I have implemented a login form that includes error validation from the backend. Ho ...

Navigating to another division segment within an HTML document using the arrow keys: a guide

There are three main div boxes colored pink, red, and green.  I would like to enable movement of all segments using arrow keys. When the page is loaded, the active box will initially be in the 'pink' segment at the center. We can then navigate ...

The FatSecret Sharp API does not support starting an asynchronous operation at the current moment

I'm currently working on an ASP.NET project where I need to integrate the Fatsecret API using a wrapper called FatSecret Sharp. However, when attempting to make a server side method call from my JavaScript script, I encounter an error. I am seeking gu ...

javascript - The window.onload event is not firing

I am currently working on developing a tool that will allow users to export a PDF file. There are two scenarios to consider: The first scenario involves a straightforward process where the user clicks the export button, and a new blank window opens imm ...

An innovative concept of housing two distinct retailers under one app

I am facing an issue with my vue.js application that consists of a landing page, user dashboard, and admin dashboard. Each section has different states, but they all share a common shared module with important data like page width, token, current user, etc ...

How come the error message in AngularJS is appearing as blank during error handling?

When utilizing AngularJS code to send a request to the server, everything works smoothly on success. However, deliberately redirecting the request to a different domain causes the CORS problem where the error handling function is triggered but errorData ...

Achieve equal distribution of divs with a specified size

After searching through various questions, none of the answers provided a solution that worked for my specific situation. Within my project, I have a series of divs, each with a fixed width of 210px. The container holding these divs is able to resize bas ...