When a user clicks on a list item, a class is added to change the background color of that particular item while simultaneously removing the class from other list items

add image description hereI'm attempting to apply a class to the list item in an unordered list when clicked, while simultaneously removing the same class from the other list items.

I've tried using the JavaScript logic below, but I'm not achieving the desired outcome. When I include e.preventDefault(), it prevents me from redirecting to the desired page, but successfully adds and removes the class from the list items. However, when I exclude e.preventDefault(), it redirects me to the desired page but does not add or remove the class.

var links = document.querySelectorAll('li');
links.forEach(function(element) {
  element.addEventListener('click', function(e) {
    // PreventDefault to prevent redirect
    e.preventDefault();
    links.forEach(async function(element) {
      // element.preventDefault()
      await element.classList.remove('active');
    });
    this.classList.add('active');
  });
});
li:hover:not(.active) {
  background-color: rgb(91, 19, 114);
  border-radius: 2vh;
}

.active {
  background-color: rgb(132, 2, 175);
}
<div id="user-account-menu">
  <ul class="side-nav">
    <li class="">
      <a href="/me">
        Settings
        <img class="navItems-icons" src="img/icons/settings.png" alt="settings">
      </a>
    </li>
    <li class="active">
      <a href="/create-user">
        Create User
        <img class="navItems-icons" src="img/icons/create-user.png" alt="create-user">
      </a>
    </li>
  </ul>
</div>

Answer №1

Kindly omit async/await from the internal forEach loop. The absence of async/await will ensure that it runs synchronously before the default behavior (redirecting) is triggered.

I experimented with this approach, and it indeed works. It removes the 'active' class from the other list items before redirection (there is a brief moment where this is visible).

UPDATE: After the OP requested the content to be displayed on the right while keeping the links visible on the left, I made adjustments to my solution. I introduced a frame for the content and directed the links to that specific content area.

var links = document.querySelectorAll('li');
links.forEach(function(element) {
    element.addEventListener('click', function(e) {
        links.forEach(async function(element) {
            element.classList.remove('active');
        });
        this.classList.add('active');
    });
});
li:hover:not(.active) {
  background-color: rgb(91, 19, 114);
  border-radius: 2vh;
}

.active {
  background-color: rgb(132, 2, 175);
}

#container {
  display: flex;
}

iframe[name=page-content] {
    flex: auto;
}
<div id="container">
    <div id="user-account-menu">
        <ul class="side-nav">
            <li class="">
                <a href="https://example.com/" target="page-content">
                    Settings
                    <img class="navItems-icons" src="img/icons/settings.png" alt="settings">
                </a>
            </li>
            <li class="active">
                <a href="https://wikipedia.com/" target="page-content">
                    Create User
                    <img class="navItems-icons" src="img/icons/create-user.png" alt="create-user">
                </a>
            </li>
        </ul>
    </div>
    <iframe name="page-content"></iframe>
</div>

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

The Chart.js donut chart is not displaying as expected on the HTML page when using

My HTML code is set up to display a donut chart with database records retrieved through a PHP script. The data is successfully fetched and visible in the browser console, but the chart itself is not showing up. How can I resolve this issue? console.lo ...

When an element is appended, its image height may sometimes be mistakenly reported as

I am dynamically adding divs and I need to retrieve the height and width of an image. Based on this information, I have to apply CSS to the MB-Container class. For example: if the image is portrait orientation, set container width to 100%. If it's ...

Uploading images simultaneously while filling out a form

Currently, I have a form that requires users to fill it out and upload an image. However, there is a delay of up to 30 seconds when the user hits "Submit" due to the image size being uploaded. I'm interested in finding a way to initiate the image upl ...

Form with upload and submission options

I need your assistance with PHP. I want to create a form that includes both an upload button and a submit button. Is it possible to have two button elements within one form, or do I need to separate them into two separate forms - one for the upload butto ...

The error message "Cannot read property 'data' of undefined" is commonly seen in Vue.js when using Axios

I am encountering an issue where the JSON data is not displaying in cards or list format after performing a search. The search functionality appears to be working as I can see the API call with the search text in the console. However, nothing is being disp ...

displaying a PDF file in Safari

Is there a way to display a PDF document within an HTML page without encountering a missing plugin error? I attempted to use the following code, but the error persists. Interestingly, if I drag the same PDF file directly into my browser, it displays perfe ...

Obtaining req.body twice while handling a 307 redirect in an Express application

I have encountered a unique issue with my form submission in an express js application. Upon form submission, data is being POST to another route and then redirected back to the original route. View <form action="action" method="post> <input t ...

Effective ways to narrow down data in vuetify v-autocomplete component using Fuse.js

In my application, I am using the Vuetify autocomplete component. This component allows for the use of a custom filter to filter input data. Below is an example of a custom filter for the autocomplete: customFilter (item, queryText, itemText) { const ...

Dependencies in Scala.js for CSS styling

I am currently having an issue implementing Scala.js with the bootstrap library. Including the js file was a simple and straightforward process: jsDependencies +="org.webjars" % "bootstrap" % "3.3.7-1" / "bootstrap.js" minified "bootstrap.min.js" However ...

Manually incorporating multiple React components into a single container

I am currently in the process of upgrading an old JavaScript application that relies heavily on jQuery by introducing some React components. The existing code utilizes JS/jQuery to dynamically add elements to the DOM, and I am looking for a way to replace ...

Is it possible to reorganize the order of elements in a

My goal is to create a flex column layout where the image appears first. However, I'm facing an issue with the code below, as it only changes the order when the flex direction is set to row (image on the left). It does not work for rows. </head> ...

Is it possible to modify the parameters of a function by utilizing a MethodDecorator without affecting the "this" value?

Consider a scenario where you need to dynamically modify method arguments using a decorator at runtime. To illustrate this concept, let's simplify it with an example: setting all arguments to "Hello World": export const SillyArguments = (): MethodDec ...

PHP failing to retrieve information

Having trouble with this specific file as it seems to be missing data in the address fields. Additionally, whenever "notes" are inputted, the Address data disappears. Any thoughts on how to resolve this issue? <tbody> ' ; $message .=&a ...

Preventing Past Dates from Being Selected in JQuery Date Picker

Need help with a date picker that only allows selection of the 1st and 15th dates of each month. How can I prevent users from selecting previous dates? <link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" ty ...

Create a cookie on a subdomain that is accessible by all other subdomains

I have been working on a NextJS project that involves multiple apps on separate subdomains. My objective is to enable single sign-on so that when I log in to one app, I am automatically signed in to all the others. We are utilizing nookies as our cookie ha ...

How can I fix the alignment issue with my centered div?

My attempt to vertically align a centered inner DIV is not working as expected... What could be causing this issue? CSS Code: #page_bar { width: 100%; height: 30px; background-color: white } .page_bar { width: 800px; height: 30px; ...

Implementing a constant loop repeatedly in NextJs

I am seeking assistance with printing the <Icon /> 700 times on a single page. As a newcomer to NextJs, I have successfully used a for loop to console.log the icons but am unsure of how to actually display them. Any help would be greatly appreciated. ...

Revamp your search experience with Algolia's Angular Instant Search: Design a personalized search box template

Custom Search Box Request: My goal is to implement an autosuggest search box using Algolia Angular instant search with an Angular Material design. To achieve this, I am planning to customize the search box component by replacing the standard <ais-sea ...

JavaScript error caused by incorrect JSON parsing

Encountering Another Issue. Here's the Relevant Code: if(localStorage.getItem("temporaryArray")){ var temporaryArray = JSON.parse(localStorage.getItem("temporaryArray")); }else{ var temporaryArray = []; } Essentially, what this code snippet ...

What is the best way to create a reusable component for a Material-UI Snackbar?

Having trouble getting my Alert component to display a message that says "Successfully submitted" in the parent component. The message doesn't seem to be showing up. AlertComponent import React, { useState } from "react"; import { Snackbar, Alert } f ...