The navigation underline stays in place even after being clicked, and also appears below

Take a look at this js fiddle

I've managed to create the underline effect on the navigation links when the user hovers over them.

However, the underline only stays visible until the user clicks elsewhere on the screen. How can I make it persist as long as the user is on the page?

Additionally, there is a button in the left-side navigation that acts as a link to the home page. Despite my efforts, the underline feature does not work on this button. Any suggestions on how to fix this?

.navbar-brand img {
  height:33px;
  width: auto;
}

.navbar {
  line-height: 33px;
}

button {
    background-color:rgb(255, 102, 0);;
}
.navbar-dark .navbar-nav > li > a {
    border-bottom: 1px solid transparent;
}

.navbar-dark .navbar-nav > li > a:hover, .navbar-dark .navbar-nav > li > a:focus, .navbar-dark .navbar-nav > .active > a, .navbar-dark .navbar-nav > .active > a:hover, .navbar-dark .navbar-nav > .active > a:focus {
    color: rgb(255, 102, 0);;
    border-bottom: 1px solid rgb(255, 102, 0);
}

.navbar-dark .navbar-nav > button.home:hover, .navbar-dark .navbar-nav >  button.home:focus, .navbar-dark .navbar-nav > .active > button.home, .navbar-dark .navbar-nav > .active > a:hover, .navbar-dark .navbar-nav > .active > a:focus {
    color: rgb(255, 102, 0);
    border-bottom: 1px solid rgb(255, 102, 0);
}

HTML

<nav class="navbar navbar-expand-md fixed-top navbar-dark bg-dark">
  <a class="navbar-brand" routerLink="/" routerLinkActive="active">
    <img src="https://via.placeholder.com/200x30" alt="" />
  </a>
  <button class="navbar-toggler home" (click)="isCollapsed = !isCollapsed" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarsExampleDefault" [collapse]="isCollapsed">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item">
        <a class="nav-link" routerLink="/services" routerLinkActive="active">Products</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" routerLink="/case-studies" routerLinkActive="active">Testimonials</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" routerLink="/about" routerLinkActive="active">About</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" routerLink="/blog" routerLinkActive="active">Blog</a>
      </li>
    </ul>
    <div class="form-inline my-2 my-lg-0">
       <a class="nav-link button" routerLink="/intouch" routerLinkActive="active"><button class="btn btn-outline-primary my-2 my-sm-0">Contact</button></a>
    </div>
  </div>
</nav>

Answer №1

If you desire the hover effect to remain active even after clicking on the link, you can achieve this by using jQuery (native JS is also an option, but since Bootstrap relies on jQuery, we will stick with it) to attach click event listeners to:

  • the <a> element in your navigation bar to add a class called active to the link and prevent the click event from bubbling up to the document
  • the document object within your DOM structure to remove the active class from all navigation links

Your JavaScript logic should be similar to:

$('.navbar-nav a').click(function(e) {
    e.stopPropagation();
    $(this).addClass('active');
});

$(document).click(function() {
    $('.navbar-nav a').removeClass('active');
});

If you want only one element to maintain the active state at a time, you need to adjust the first click event handler to remove the class from other anchor elements, like so:

$('.navbar-nav a').click(function(e) {
    e.stopPropagation();
    $('.navbar-nav a').removeClass('active');
    $(this).addClass('active');
});

To enhance this, simply include a new selector a.active in your CSS list:

.navbar-dark .navbar-nav > li > a:hover,
.navbar-dark .navbar-nav > li > a:focus,
.navbar-dark .navbar-nav > .active > a,
.navbar-dark .navbar-nav > .active > a:hover,
.navbar-dark .navbar-nav > .active > a:focus,
.navbar-dark .navbar-nav > li > a.active {
    color: rgb(255, 102, 0);;
    border-bottom: 1px solid rgb(255, 102, 0);
}

Check out the proof-of-concept example below:

$(function() {
  $('.navbar-nav a').click(function(e) {
    e.stopPropagation();
    $('.navbar-nav a').removeClass('active');
    $(this).addClass('active');
  });

  $(document).click(function() {
    $('.navbar-nav a').removeClass('active');
  });

});
.navbar-brand img {
  height: 33px;
  width: auto;
}

.navbar {
  line-height: 33px;
}

.footer {
  padding: 25px;
}

button {
  background-color: rgb(255, 102, 0);
  ;
}

.navbar-dark .navbar-nav>li>a {
  border-bottom: 1px solid transparent;
}

.navbar-dark .navbar-nav>li>a:hover,
.navbar-dark .navbar-nav>li>a:focus,
.navbar-dark .navbar-nav>.active>a,
.navbar-dark .navbar-nav>.active>a:hover,
.navbar-dark .navbar-nav>.active>a:focus,
.navbar-dark .navbar-nav>li>a.active {
  color: rgb(255, 102, 0);
  ;
  border-bottom: 1px solid rgb(255, 102, 0);
}

.navbar-dark .navbar-nav>button.home:hover,
.navbar-dark .navbar-nav>button.home:focus,
.navbar-dark .navbar-nav>.active>button.home,
.navbar-dark .navbar-nav>.active>a:hover,
.navbar-dark .navbar-nav>.active>a:focus {
  color: rgb(255, 102, 0);
  border-bottom: 1px solid rgb(255, 102, 0);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js"></script>

<nav class="navbar navbar-expand-md fixed-top navbar-dark bg-dark">
  <a class="navbar-brand" routerLink="/" routerLinkActive="active">
    <img class="vp-image" src="http://via.placeholder.com/200x30" alt="Dev" />
  </a>
  <button class="navbar-toggler home" (click)="isCollapsed = !isCollapsed" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarsExampleDefault" [collapse]="isCollapsed">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item">
        <a class="nav-link" routerLink="/services" routerLinkActive="active">Services</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" routerLink="/case-studies" routerLinkActive="active">Case Studies</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" routerLink="/about" routerLinkActive="active">About</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" routerLink="/blog" routerLinkActive="active">Blog</a>
      </li>
    </ul>
    <div class="form-inline my-2 my-lg-0">
      <a class="nav-link button" routerLink="/intouch" routerLinkActive="active"><button class="btn btn-outline-primary my-2 my-sm-0">Contact</button></a>
    </div>
  </div>
</nav>

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

Adjusting the desktop view through media queries for mobile devices

As someone with no coding experience, I've been working on my portfolio using Cargo. Currently, I'm trying to adjust the mobile view of an article on my homepage through media queries. However, the code is unintentionally changing the layout on d ...

Mastering the art of integrating two applications in Django involves understanding how to properly

Hey there, I'm currently diving into Django and I have a question regarding making my two apps work together. Here's how my folders are structured: mysite/ --/app1 (blog app) --/app2 (a list of users that sign up with a form) --/mysite --db --m ...

The Next.js client-side JavaScript application experiences unforeseen disruptions without generating any console errors

My server is responsible for constructing HTML from a JSON response: { content: "<div id=\"_next\">...</div>...<script src=\"...\"></script>" } This is how my Node server handles the data: const output = "&l ...

Transition delays in Tailwind CSS when dark mode is activated

My dark mode toggle is functioning with the following CSS: :root { --primary: var(--white); } .dark { --primary: var(--black); } However, when I include the following code: * { @apply transition-colors duration-700; } The background colors of ...

FirebaseError encountered: Unable to update document due to absence of document. Updating document is only possible if document id is hard coded

For my latest project, I have a component that can successfully create a new user and add them to the database using the function createUserWithEmailAndPassword(auth, email, password). Now, I am working on another component that will allow users to edit t ...

In need of secure HTML, received a dose of Style instead

I am currently developing a component that loads html content dynamically and validates the loaded styles to prevent any mixing of app styles with the dynamic template's styles. This is the structure of my HTML component: <div class="modal-header ...

Is there a way to prevent a span from appearing at the end of a line?

Imagine a scenario where I have a paragraph with various span elements that are styled using classes. What if there are numbers interspersed within the text for easy reference, and I want to ensure they do not end up at the end of a line? For example: 1 ...

Error encountered when trying to update tree structure in TypeScript with new data due to incorrect array length validation

I have encountered an issue with my tree data structure in TypeScript. After running the updateInputArray(chatTree); function, I am getting an “invalid array length” error at the line totalArray.push(iteratorNode.data);. Furthermore, the browser freeze ...

What is the best way to darken the background when an alert is displayed and disable the dimming effect when the alert is closed?

Here's the JavaScript snippet I'm using: reset.addEventListener("click", function(){ document.querySelector("#body").classList.add("darkenPage"); myReset(); alert("Reset Successful!!"); document.querySelector("#body").classList.re ...

Can you explain the process that takes place when require("http").Server() is called with an Express application passed in as a parameter?

As I was exploring the Socket.io Chat Demo found at this link: http://socket.io/get-started/chat/, I came across their require statements which left me feeling confused. var app = require('express')(); var http = require('http').Server ...

Utilize React Dropzone for effortlessly styling elements upon drop action

Currently, I am working on implementing Dropzone in React. My specific requirement is to display a text and a blue border in the center of the Dropzone area when files are dragged onto it (text: "you are inserting files"). This is how my current code look ...

What is the best way to allow all authenticated routes to display the Devise ajax Login form?

I have successfully incorporated Devise to accept Ajax Login and have designed a form for logging in via ajax, displayed within a modal. However, I am only able to view the form and login when I set up event binders for specific buttons that activate the m ...

The duplication and multiplication of margin-left is occurring

I am baffled by the fact that margin-left is only affecting certain elements and causing frustration. .setting-container { position: relative; top: 60px; left: 0px; width: 100%; height: calc(100% - 60px); } .setting-topnav { width: 100%; h ...

The command "bin" is not identified as an internal or external command in this npm script

I'm new to using node/npm and encountering an issue when attempting to start an npm script. Every time I try to execute a simple script like the one below, I get the error message "bin is not recognized as an internal or external command." I have suc ...

You need a function property for the child component to be updated

I recently encountered an unusual issue with my React components that has left me puzzled. Here is a condensed version of the app: class Child extends React.Component { componentDidUpdate(prev) { if (!prev.isActive && this.props.isActive) ...

Issue with scrolling to the bottom of collapsed sections in Bootstrap

I have a bootstrap collapse panel and I've added a toggle link at the bottom to allow users to expand and collapse the content with a click. The Issue My problem arises when the menu expands, causing it to scroll all the way to the bottom of the pag ...

The XPath for the element that comes before a specific text

Looking for the XPath of the following code snippet: <a class="account-name" long-text="Sample Text" ng-click="accountClick(account)" ng-href="sample URL" href="sample URL1"> <span>Plan Name</span></a> I attempted this: //span[te ...

How to show a button within a table cell using AngularJS?

The AngularJS application developed by my company was recently handed over to me for further development. Currently, I am working on integrating a navigation button in a table cell that will allow users to navigate to custom pages of their choice. Within ...

Encountering the error "Unable to access the 'pickAlgorithm' property of null" in a ReactJS context

Encountering an issue during npm install process. npm install -g netlify-cli The error message displayed is: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d1a2a5b0a5a2b5fcb2bdb8b4bfa591e1ffe5ffe6"> ...

Troubleshooting JSONP Implementation with JQuery: Scope versus Async Problems

I've been trying to call a JSONP service using the $.ajax function: $.ajax({ url: jsonpURI, dataType: "jsonp", jsonpCallback: callback, success: function () { console.log("Success"); }, error: function (err) { ...