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

Implement the map function to validate every input and generate a border around inputs that are deemed invalid or empty upon button click

Currently, I'm in the process of developing a form with multiple steps. At each step, when the next button is clicked, I need to validate the active step page using the map function. My goal is to utilize the map function to validate every input and ...

Exploring how AWS Lambda can be integrated into a Node.js project deployed on Elastic Beanstalk

I have been using a thumbnailing function on lambda, but now I want to transition it to elastic beanstalk. However, when I deployed the function to beanstalk, it did not work as expected because lambda handled many background tasks for me. My lambda funct ...

What is the best way to activate CSS filters on VueJS once the project has been compiled?

While working on a Node server locally, my SVG filter functions properly. However, once I build the project and run it on a server, the filter stops working. This VueJS project is utilizing Webpack as its build tool. The process of building the app invol ...

The div is not displaying the background image as intended

.cover-image { margin-bottom: 0px; height: 350px; color: white; text-shadow: black 0.3em 0.3em 0.3em; } <div class="cover-image" style="background: url('~/images/hdpic.jpg') no-repeat; background-size:cover"> </div> I&apo ...

Why is my nodejs crypto decipher not working properly?

I've come across some encrypted data that looks like this: U2FsdGVkX1+21O5RB08bavFTq7Yq/gChmXrO3f00tvJaT55A5pPvqw0zFVnHSW1o To decrypt it, I use the password: password (this is just an example from gibberish-aes) When I try to decrypt it using the ...

Creating a phonecat application using Angular on a node server

As a newcomer to Angular, I am currently in the process of setting up the Angular phonecat application. To begin with, I downloaded the code from this location: https://docs.angularjs.org/tutorial/ After that, I installed Node.js on my system. Now, I a ...

Unable to locate Socket.io resource at path: "/socket.io/1/?t=..."

I am currently working on transitioning my initial node/socket.io application from functioning locally to operating remotely on a server. The socket.io server has been successfully launched: var socket = require("socket.io").listen(4545); The client has ...

Ways to categorize items using JQuery based on their hierarchical structure

I am looking to organize the following HTML content: <h2>State the Issue  </h2> <h3>Provide information about your objective</h3> <h3>Share any error messages received</h3> <h2>Outline Your Attempts  ...

Using dustjs-linkedin alongside express version 3

Attempting to integrate dustjs-linkedin with an express 3 project, encountering a persistent error: Error: Template name parameter cannot be undefined when calling dust.compile at Object.compiler.compile (/home/user/project/node_modules/dustjs-linkedin/li ...

Creating columns with equal heights in Bootstrap 3 without compromising on the column padding

I am using a standard Bootstrap 3 CSS setup and I am trying to give columns inside a row the same height. I have been experimenting with using display: table and display: table-cell, which does work, but it seems to add vertical padding to columns with les ...

Opacity transition in CSS does not function properly on a sibling selector when hovering over an element

I have created a responsive menu where the list items after the 4th element are set to display:none; opacity:0 on mobile devices. The 4th element is an icon and when you hover over it, the hidden menu items appear as a block list below using li:nth-child( ...

Customizing styles in ZK based on theme

I am currently working on a ZK application that has been styled using CSS, specifically the colors from the Sapphire theme. My goal is to have environment-dependent themes - Sapphire for production and Breeze for stage. While I have successfully implemente ...

A guide on Implementing PastBack Functionality with AJAX Responses

When I make a GET request for an HTML page, I come across the following element: <a id="ctl00_cphRoblox_ClaimOwnershipButton" href="javascript:__doPostBack('ctl00$cphRoblox$ClaimOwnershipButton','')">Claim Ownership</a> My ...

Create a PDF document using a combination of charts and tables

When I try to create a PDF file with both the chart and table embedded, only the table is showing up. Can someone please provide me with some suggestions on how to resolve this issue? JSFIDDLE LINK ...

Trouble with using $.ajax to call a PHP function

Hey everyone, I hate to ask for help but I'm really stuck on this issue. I've tried everything and followed all the scenarios on this site, but I just can't seem to get it working. I even added alerts and echoes, but the function doesn' ...

Problem with Bcryptjs Async Implementation

I have implemented a function in my node server using bcryptjs to hash and compare passwords. Here is the code snippet: this.comparePasswords = function(password1, password2, callback) { bcrypt.compare(password1, password2, function(error, result) { ...

Encountering an illegal invocation error in jQuery

Recently delving into the world of jQuery, I am attempting to call a C# function from JavaScript using AJAX and jQuery. Additionally, I need to pass some parameters while making the call to the C# function. Here is how I am attempting to achieve this: var ...

Using jQuery to Validate Input Text Control Depending on Radio Selection

How can I ensure that the input text linked to the selected radio option is filled in? For instance, in the example above: If Contact 1's Email radio option is chosen, the Email text field for Contact 1 must not be empty, while the Phone and US Mai ...

Customize your Outlook emails with HTML and CSS to right-align content for a polished look

My current project involves generating a report to be sent via email, with Outlook being the mandatory application in our system. The report's content is HTML-based and utilizes a table layout. Part of the content needs to appear right-aligned within ...

I was confused about the distinction between the https.get() and https.request() functions in the Node.js npm package for https

// # Exciting Nodejs Programs! const https = require('https'); https.get('https://www.google.com/', (res) => { console.log('statusCode:', res.statusCode); console.log('headers:', res.headers); res.on ...