What is the best way to implement the Active list element feature in my menu bar?

The current list element is :

<li class="nav__item"><a class="nav__link nav__link--active " href="#"...

The standard list element is:

<li class="nav__item"><a class="nav__link " href="#"...

I want the element to be active when selected and normal when not selected.

Here is the provided code snippet:

<div class="nav-section">
  <div class="nav-section__header">
    <h2 class="nav-section__title"> Heading </h2>
  </div>

  <ul class="nav">

    <li class="nav__item ">
      <a class="nav__link nav__link--active" href="../home/main1.php">
        <span class="channel-link__icon">
<span class="channel-link__element">Title1</span>
      </a>
    </li>

    <li class="nav__item ">
      <a class="nav__link nav__link--active" href="../home/main2.php">
        <span class="channel-link__icon"></span>
        <span class="channel-link__element">Title2</span>
      </a>
    </li>
  </ul>

Answer №1

If you are using plain JavaScript, you can store the nav__link elements in an array and then update the active state by removing the active class from all elements and adding it to the clicked one.

Here is an example:

Sample HTML

<a class="nav__link nav__link--active" onclick="toggle(this)" href="../home/main2.php">
    <span class="channel-link__icon"></span>
    <span class="channel-link__element">Title2</span>
</a>

JavaScript Function

function toggle(element) {
    var links = document.getElementsByClassName("nav__link");
    for(var i = 0; i < links.length; i++) {
        links[i].classList.remove("nav__link--active");
    }
    element.classList.add("nav__link--active");
}

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

Retrieve the position of an element using Python and selenium

Currently, I am working on a project and need to extract the location and size of an element using the following xpath: "//div[@class='titlu']" Upon inspection, it appears that the element is visible with no distinct features. However, I have e ...

Issue with retrieving Combobox value within AngularJS ng-repeat generated table using ng-model

Here is my code that I need help with: <thead> <tr> <th>Id Detalle_Venta</th> <th>Id Producto</th> <th>Producto </th> <th>Cantidad </th> <th>Direccion </th> ...

Issue encountered when retrieving data from a cross-domain AJAX request

I am currently developing a web application where I need to showcase information on a map. In order to do so, I have to convert coordinates from EPSG:3301 to EPSG:4326. There is a useful website that can help with this conversion: {"geometry":{"type":"Poin ...

When converting a block formatting context into a block, the margin does not collapse

It seems that the behavior of margins collapsing between block elements inside and outside a BFC is not as straightforward as expected. For instance, when a button element's display property is set to inline-block, it forms a BFC, which should prevent ...

Using the symbol for pi in a JavaScript program rather than its numerical value, while still performing calculations with the numerical value behind the scenes

I am working on a calculator project where I want the symbol for pi to be displayed instead of the numerical value. Here is the relevant function: function Pi(pi) { document.getElementById('resultArea').innerHTML += pi; eval(document.ge ...

Sharing Iframes across various Components within a Single Page Application (like Youtube)

Did you know that Youtube now lets you minimize the player while browsing the site? It's similar to the functionality on LolEsports.com with Twitch and embedded Youtube players. I'm interested in adding this feature to my own website. Here' ...

Encountering an issue while fetching information from a JSON file using JavaScript

I am encountering an Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data let mydata = JSON.parse("file.json"); console.log(myJSON) Here is a sample of the JSON file's data: [[1,1,0,1,1,0,0,0,1,1,1,1,1, ...

Creating a visual comparison by using knockout side by side

I'm currently working on a project that requires me to display multiple items side by side for comparison. The ideal layout would be similar to Amazon's, where each item is represented by a vertical column with all relevant information about tha ...

Creating randomized sequences using JavaScript

One of my hobbies involves organizing an online ice hockey game league where teams from different conferences compete. It's important to me that every team gets an equal number of home and away matches throughout the season. To simplify this task, I&a ...

Can the caller function's arguments be altered using Function.prototype.apply()?

function modifyValues(a,b){ console.log(arguments); //["oldValue","oldValue"] var newArguments = updateValues.apply(this,arguments); for (var i=0;i<arguments.length;i++){ arguments[i] = newArguments[i]; } console.log(arguments); // ...

How to Execute Another JavaScript Script Using IF/ELSE Statement?

I am trying to dynamically call one of two JavaScript files based on a condition. Here is the code I have: <script type="text/javascript"> if(b_condition) <script type="text/javascript" src="http://script1.js"></script> else <scri ...

I'm looking to transfer my stringified object into the HTML body. How can I achieve

When sending an HTML file to a client using the res.write() method, I also need to include an object within the HTML. However, when I stringify the object and add it along with the HTML, the JSON object ends up outside of the HTML structure. I require the ...

Breadcrumb navigation that is determined by data hierarchies and relationships between parent and child items

I am looking to implement a dynamic breadcrumb system on my website using data-driven methodology. The necessary data is stored in a MariaDB database and has the following structure: parent_id | parent_name | child_id | child_name ——————— ...

In React, the entire component refreshes every time the modal is opened

<ThemeProvider theme={theme}> <GlobalStyle /> {componentName !== 'questionaire' && componentName !== 'activityResult' && <CardWrapper />} <ErrorModal ...

Step-by-step tutorial on designing an input slider to dynamically adjust the CSS :before linear-gradient values

Is there a way to achieve a gradient effect using pseudo-element :before on an image that can be customized by adjusting a slider input? I've been trying to implement this feature with the following code, but have not been successful so far. var ...

Tactics for postponing a js function post-click

I need to implement a delay after clicking a button to fetch some data. The code will be executed within the browser console. $(pages()) is used to retrieve the pagination buttons. let calls = []; for (let i = 1; i <= callPagesCount; i++) { ...

The resizing of the background image is contingent upon the size of the

I am facing an issue with my bootstrap carousel. One of the items only contains a background image without any content. I have set a height for it so that it is still visible even without content. However, when viewing on mobile devices, I can only see a p ...

White border appears when hovering over MUI TextField

I've been troubleshooting this issue for what seems like an eternity. I've combed through Chrome's inspect tool, searching for any hover styles on the fieldset element, but to no avail. Here's my dilemma... I simply want a basic outline ...

The dropdown menu in codeigniter is not displaying the selected option

When using a drop-down button to select an option from the available choices, I encountered a problem where the selected option was not displayed in the box. Additionally, it only allowed me to make one selection. The data for the drop-down menu is retriev ...

What is the proper way to specify the type for a <video> element reference in React when utilizing Typescript?

I have been experimenting with controlling the play/pause state of a video in React.js using ref's. My code functions correctly but I am encountering tslint errors that I am currently trying to diagnose: function App() { const playVideo = (event:a ...