Updating the color scheme of the selected nav-item and showcasing the corresponding page in relation to the navbar selection

I have been trying various methods, but I am unable to change the background color of an active navigation item and also display the corresponding page.

Important: The jQuery code below successfully changes the background color of the navbar list item. However, whenever I click on the page, it reverts back to the default color. If I include 'e.preventDefault()', the background color changes correctly but the page relative to the navbar item does not display.

HTML (EJS file)

 <div class="navbar-nav">
    <ul class="navbar-nav">
        <li class="nav-item">
            <a class="nav-link" href="#">Item 1</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="#">Item 2</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="#">Item 3</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="#">Item 4</a>
        </li>
    </ul>
</div>

CSS

.navbar-nav > .aMenuActive {
    background-color: var(--main-pink-color);
}

JQuery

// aMenuActive -> Add class to clicked li
$('ul.navbar-nav > li').click(function (e) {    
    console.log("log...clicked menu",);
    $('ul.navbar-nav > li').removeClass('aMenuActive');
    $(this).addClass('aMenuActive');
    //e.preventDefault(); // -> works but does not send to link
});

$('ul.navbar-nav > li').click(function (e) {    
    console.log("log...clicked menu",);
    $('ul.navbar-nav > li').removeClass('aMenuActive');
    $(this).addClass('aMenuActive');
    //e.preventDefault(); // -> works but does not send to link
});
.navbar-nav > .aMenuActive {
    background-color: red;
} 
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="navbar-nav">
    <ul class="navbar-nav">
        <li class="nav-item">
            <a class="nav-link" href="#">Item 1</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="#">Item 2</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="#">Item 3</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="#">Item 4</a>
        </li>
    </ul>
</div>

Answer №1

By using href, the page will reload and the selection will be lost.

You have the ability to adjust the background color solely through CSS.

.navbar-nav > .nav-item:focus-within {
  background-color: pink; //var(--main-pink-color);
} 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="navbar-nav">
  <ul class="navbar-nav">
    <li class="nav-item">
      <a class="nav-link px-auto px-lg-2 px-xl-3" href="/index/2">Item 1</a>
    </li>
    <li class="nav-item">
      <a class="nav-link px-auto px-lg-2 px-xl-3 " href="/index/viagens">VIAGENS</a>
    </li>
    <li class="nav-item">
      <a class="nav-link px-auto px-lg-2 px-xl-3" href="/index/3">Item 2</a>
    </li>
    <li class="nav-item">
      <a class="nav-link px-auto px-lg-2 px-xl-3" href="/index/4">Item 3</a>
    </li>
  </ul>
</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

What is the best way to create a timer using JavaScript?

I'm looking for a reverse timer to track session timeout. I found a code on codepen that works as a clockwise timer, but my attempts to make it counterclockwise have failed. Can someone please suggest a solution? I want the timeout to be either 1 hour ...

Struggling to properly implement background images in a React application using Tailwind CSS

I'm currently developing a React application using Tailwind CSS for styling. In my project, I have an array of items called "trending," and I'm attempting to iterate through them to generate a series of divs with background images. However, I am ...

Monitoring of access controls on Safari during uploads to S3

Safari 10.1.2 Encountering an issue intermittently while attempting to upload PDF files to S3 using a signed request with the Node aws-sdk. Despite working smoothly 90% of the time, have been pulling my hair out trying to resolve this problem. Could it be ...

Menu Items at the Center

I am currently working on a Wordpress website and struggling to center the menu items that are currently aligned to the left. I have created a child theme from the existing theme's code, but still can't figure out how to achieve this simple task. ...

Errors arise when trying to play an audio file using Discord.js

Hello everyone, I have a problem that I need help with. I'm trying to play audio in a voice channel on Discord, but I keep encountering issues. After connecting to the channel, whenever I try to play an audio file, it crashes. Additionally, when insta ...

Ways to determine the number of duplicate items in an Array

I have an array of objects that contain part numbers, brand names, and supplier names. I need to find a concise and efficient way to determine the count of duplicate objects in the array. [ { partNum: 'ACDC1007', brandName: 'Electric&apo ...

Node.js is able to read an HTML file, but it seems to have trouble locating and loading

Struggling to load a jQuery file or any file in a node.js read HTML document. After spending considerable time on this issue, I realized that the Google-hosted library file works fine but my local file does not. The problem seems to be related to directing ...

Instead of just redirecting to the page, consider using Express to send the page as data to the success callback of an Angular $

Once the user has been validated, the client will receive the contents of home.html in the result variable instead of being redirected to the home.html page. Client-side request: $http({ method: "post", url: "http://localhost:2222/validateUser", data: { ...

What is the best way to expand my container element and add margins to the top and bottom?

Currently, I am utilizing the Material-UI library in combination with ReactJS, but facing some challenges pertaining to flexbox. The objective is to position my Item Container at the center of my div, extending it to occupy the entire available height whi ...

Leverage the power of Angular and Node.js to dynamically generate and configure a new subdomain on an

Currently, I am tackling a project that involves generating sub domains dynamically based on the prefixes entered by users on my website. While everything is functioning properly on my localhost using diet.js and express-subdomain, errors are being encount ...

Exploring interactions with various divs and elements through click events

Hello, I am completely new to jQuery and have encountered a roadblock! First, let me describe my document and what I am trying to achieve. Within my document, I have a set of six buttons. Each button corresponds to a different div containing content that ...

Error in form action when generated through an ajax partial in Ruby

I am facing an issue with a form that is loaded via an ajax partial. The problem arises when the form loads through ajax as it targets the wrong controller/url instead of the intended one. Despite my efforts to set the target controller correctly, it keeps ...

Implement Varnish cache tool in conjunction with Node.js and Nginx for optimal performance

I have set up two Node.js servers on different ports (3636, 4646) and configured Nginx as a reverse proxy for them. Now I am looking to add Varnish cache tool to both servers. Below is the configuration for /etc/nginx/sites-enabled/yourdomain: upstream a ...

Encountering a syntax error while utilizing a JavaScript variable in a jQuery selector for a lightbox feature

I'm currently working on creating a lightbox feature and have reached the stage where I am implementing next and previous buttons to navigate through images. I am utilizing console.log to check if the correct href is being retrieved when the next butt ...

Error Handling with PHP's die() Command

There seems to be an issue that I am facing with the die() commands. On my website, I have a member registration page which includes a form. The form's action leads to another PHP script. However, when the form is submitted, instead of displaying an a ...

What is the method for verifying a particular field in a MongoDB document with the use of Express and Passportjs?

I am currently working on a NodeJS Web application with various modules such as express, mongoose, and passportjs. Within my database, I have two types of users: regular Users and Admins, each with their own respective collection. User Admin After succe ...

After the submit button is disabled, the form fails to be submitted

Hello, I am having an issue with disabling my button after the form is submitted. The button gets disabled, but the PHP code does not execute. I have tried various scripts from the internet, but they all seem to have the same result: the button gets disab ...

What is the best way to incorporate multiple conditions within a React component?

When working in React, I have the ability to conditionally render any div using the following code snippet: {hasContent && <span>{value}</span> } Recently, I attempted to include two conditions as follows: {hasContent || hasDesc &am ...

The JQuery error encountered was due to a missing colon after the property ID

I'm currently working on some jQuery code that is supposed to hide one paragraph and show another when a specific action is triggered. I have created a class called "showp" which displays the targeted paragraph while ensuring that other paragraphs are ...

Error: Heroku Unable to Locate Module (Model File)

I encountered a model import error in my Node.js application while deploying to Heroku. 2016-02-10T20:40:04.712617+00:00 app[web.1]: > node ./bin/www 2016-02-10T20:40:04.712615+00:00 app[web.1]: > <a href="/cdn-cgi/l/email-protection" class="__cf ...