Tips on applying the "activate" class to a Bootstrap navbar in Angular 2 when implementing page anchor navigation

As I work on my single-page website using Angular 2 and Bootstrap 4, I have successfully implemented a fixed navbar component that remains at the top of the page. Utilizing anchor navigation (#id), the navbar allows smooth scrolling to different sections on the same page without needing a routing module.

The code for the navbar can be found below:

<nav class="navbar navbar-default fixed-top navbar-inverse navbar-toggleable-md">
  <div class="container">

    <div class="navbar-header">
      <button class="navbar-toggler navbar-toggler-right btn btn-outline-secondary" (click)="isCollapsed = !isCollapsed" [attr.aria-expanded]="!isCollapsed" aria-controls="collapseExample">
        <i class="fa fa-bars" aria-hidden="true"></i>
      </button>
      <a class="navbar-brand" href="index.html">Garatéa</a>
    </div>

    <div id="collapseExample" class="navbar-collapse collapse" [ngbCollapse]="isCollapsed">
      <ul class="nav navbar-nav ml-auto">
        <li class="nav-item"><a class="nav-link" href="#home">Home</a></li>
        <li class="nav-item"><a class="nav-link" href="#about">About</a></li>
        <li class="nav-item"><a class="nav-link" href="#team">Team</a></li>
        <li class="nav-item"><a class="nav-link" href="#contact">Contact</a></li>
      </ul>
    </div>
  </div>
</nav>

Each link within the navbar corresponds to a section on the website, such as the 'home' section template shown below:

<div id="home" class="text-center home-background">
  <div class="overlay">
    <div class="content">
      <h1>Welcome to <strong><span class="title-text">Garatéa</span></strong></h1>
      <p class="lead">We are an initiative that focuses on <strong>increasing survival rates</strong> in medical emergencies.</p>
    </div>
  </div>
</div>

I am seeking advice on how to dynamically highlight the corresponding link in the navbar based on the section of the website currently being viewed. For instance, when on the 'about' or 'team' section, I envision adding an active CSS class to the respective navbar link:

<li class="nav-item active"><a class="nav-link" href="#about">About</a></li>
.

Answer №1

To access the srcElement when clicking on an <a> tag, you can use the following method:

<a class="nav-link"(click)="clickedLink($event)">Início</a>
<a class="nav-link"(click)="clickedLink($event)">Início</a>
<a class="nav-link"(click)="clickedLink($event)">Início</a>

The function will look like this:

clickedLink(e){
let element = e.srcElement;

console.log(e)
for(let i=0; i <element.parentElement.children.length ; i++){
  if(element.parentElement.children[i].classList.contains('active')){
    element.parentElement.children[i].classList.remove('active')
  }
}
element.classList.add('active');

}

SEE LIVE DEMO

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

Using a custom HTML file as a container in an Android WebView

I am trying to include each loaded page within my own custom HTML file. My app needs to first parse the loaded page, select the body tag, insert it into my custom HTML file, display it in a WebView, and continue this process for each subsequent page. I h ...

Having trouble with Bootstrap not hiding on small screens as intended?

I'm not sure if the issue is related to my browser, but I need the first pills-tab to be hidden on small screens and visible on medium to larger screens. The second pills-tab should be visible on small screens and hidden on larger screens. <!D ...

How can I create responsive buttons with icons using material-ui?

I'm working with a material-ui Button that has a startIcon, and I need to hide the button text on smaller screens while still showing the icon. One common solution would be to use the useMediaQuery hook to identify the browser size and render a diffe ...

Ensuring Uniform Column Height in Bootstrap 4 - Preventing Buttons from Being Forced to the Bottom of

Using the Bootstrap 4 class 'h-100' to ensure equal height for all three columns, I encountered an issue where the buttons that were initially aligned to the bottom of each div are no longer in correct alignment. How can I maintain button alignme ...

Encountered an issue while trying to install and run an Angular app: Error code TS2694 indicates that the Namespace does not have an exported member '

Attempting to construct and execute this angular project. Post building the project, with npm i I encountered some warnings, but no errors were found. After executing ng serve -o, the following errors appeared. Moreover, when accessed through the browser, ...

Embed Javascript Code Within Text Field

Is there a way to incorporate this JavaScript into the "price" text value? Below is the code snippet: <script> function myFunction() { var x = document.getElementById('car-select')[document.getElementById('car-selec ...

Setting up a responsive footer using Bootstrap and responsive design involves following a few key steps

Seeking assistance with making the footer of my website responsive using a combination of Bootstrap and custom CSS. I am aiming for a result similar to the examples shown below, both optimized for Desktop and Mobile platforms. Your help in achieving this ...

transforming an angularJS directive into an angular6 component/directive

I have inherited an angularJS directive from an old application that I need to convert to angular6. Since I am not familiar with angularJS and only work with angular6, I am seeking guidance on how to proceed. Below is the existing angularJS code: define ...

Using Javascript to convert numerical input in a text box into its corresponding letter grade

I have been working on this code, but I am facing some issues with displaying the result. My goal is to input a number, such as "75", click a button, and have the bottom textbox show the corresponding letter grade, starting with "C" for 70-80 range. Here i ...

How to Centre Align Items in a React Native ListView

Is there a way to center align the items in a ListView without using another View wrapping the ListView? Currently, all the items are left aligned. ListView Code Snippet <ListView dataSource={this.state.dataSource} renderRow={this.renderItem} ...

How to Spin an Image in the Canvas Using HTML5

I am having trouble rotating an image inside a canvas after researching similar questions on Stack Overflow. Here's what I've learned: It seems I cannot rotate a single object inside the canvas. I can only rotate the entire canvas itself. ...

Encountering a challenge when trying to showcase data from a saved .txt file within a bootstrap card

I encountered a minor problem in my PHP project. I developed a small application that allows users to fill out form fields and stores all the data in a .txt file. Simultaneously, the entered data is displayed below the form with specific details such as fi ...

The creation of an Outlook 365 add-in using Angular8 presents challenges when attempting to delete a cookie that was generated with ngx

I have developed an Office 365 add-in for Outlook. The add-in is built using Angular8 and I am utilizing ngx-cookie-service to store my authentication token information in a cookie. Despite being able to install the add-in, store the auth token in the co ...

Transferring information from an HTML form to a C# webservice through AJAX

I've created a form in HTML using Bootstrap within PHPStorm, and now I want to send the information to a C# webservice using AJAX. However, I'm unsure about what to include in the AJAX URL section (shown below). Here is the HTML/Bootstrap form I ...

The .find() function conveniently jumps over the table directly following its parent element

After clicking on Inner Add Row, the correct row is added from the .charts-series table. However, when I click on Outer Add Row, a row from the .charts-series table is added instead of one from the .charts table. Here is the link to the example: http://jsf ...

Full-screen and auto-cropping capabilities are featured in the Bootstrap 4 carousel design

Is there a way to make full-width images in the bootstrap 4 carousel cropped based on position: center, background: cover to prevent scrolling issues? I attempted to follow advice from this webpage but encountered stretching and scroll-bar problems with d ...

How to retrieve data from a JSON file in Angular 2 using the http get

I am encountering an issue while trying to access a json file using http get. The error message I receive is as follows: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterable ...

The input field cannot be accessed via touch on mobile devices

<div class="form-group row pswrd" style="padding: 0px 10px"> <div id="email" class="col-md-12 col-xs-12"> <input type="password" class="form-control c_fname" id="c" #pswd name="password" placeholder="password" [(ngModel)]="user.passwor ...

Having trouble targeting a div with jQuery

Is it possible to target a specific div within an unordered list and list items? I'm having trouble with it. Here is the HTML code: <ul class="grid"> <div id='categoria' cat='web'></div> <li id=' ...

Show Zeroes in Front of Input Numbers

I am working with two input fields that represent hours and minutes separately. <input type="number" min="0" max="24" step="1" value="00" class="hours"> <input type="number" min="0" max="0.60" step="0.01" value="00" class="minutes"> This se ...