How can the navbar class be altered when there is a change in routes?

My navbar class is set to change based on scroll position

Script

    <script>
     $(window).scroll(function () {
      if ($("#main-navbar").offset().top > 100) {
         $("#main-navbar").addClass("navbar-shrink");
      } else {
         $("#main-navbar").removeClass("navbar-shrink");
      }
    });
   </script>

HTML

      <nav class="navbar navbar-expand-lg rds-navbar py-0" id="main-navbar">
       <div class="container px-lg-0" id="navbar">
        <a class="navbar-brand mr-lg-5" [routerLink]="['en','home']">
            <img alt="ViPay" src="assets/img/logo.png" id="navbar-logo" style="height: 50px;">
        </a>
        <button class="navbar-toggler pr-0" type="button" data-toggle="collapse" data- 
         target="#navbar-main-collapse" aria-controls="navbar-main-collapse" aria-expanded="false" 
            aria-label="Toggle navigation"><span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbar-main-collapse">
           <ul class="navbar-nav align-items-lg-center">
              <li  class="nav-item  mr-4">
                  <a class="nav-link "  [routerLink]="['en','personal']" 
                 routerLinkActive="rds__navbar-active" >Personal</a>
              </li>
           </ul>
         </div>
       </div>
    </nav>

How the code functions: The page starts with a transparent navbar, which turns white as you scroll down and back to transparent when scrolling up.

Desired Outcome: For the home page, I want the navbar to be transparent at the top. On other pages, I want it to remain white even when at the top without scrolling, and stay white while scrolling.

Image Links:

Navbar appears transparent on home page at top

Navbar turns white upon scrolling down

I need this specific styling only for the home page. Any suggestions on how to achieve this would be greatly appreciated. Thank you for your help.

Answer №1

Ensure you are utilizing Angular 2 and have separate components for each page.

Each component can make use of HostListener for functionality.

    import {OnInit, OnChanges, HostListener} from '@angular/core';

    export class HomeComponent implements OnInit, OnChanges{
            constructor(){}
            ngOnChanges(){
    this.manageHeaderBackground(window.pageYOffset);
  }
            @HostListener('window:scroll')
              scroll() {
                this.manageHeaderBackground(window.pageYOffset);
              }

             manageHeaderBackground(scrollOffset: number){
                    if (scrollOffset >= 100) {
                        $("#main-navbar").addClass("navbar-shrink");
                    } else {
                        $("#main-navbar").removeClass("navbar-shrink");
                    }
             }
    }

In Other Components:

    import {OnInit, OnChanges, HostListener} from '@angular/core';

    export class OtherComponent implements OnInit, OnChanges{
            constructor(){}
            ngOnChanges(){
    this.manageHeaderBackground(window.pageYOffset);
  }
            @HostListener('window:scroll')
              scroll() {
                this.manageHeaderBackground(window.pageYOffset);
              }

             manageHeaderBackground(scrollOffset: number){
                //Add your white background here always with a class
                $("#main-navbar").addClass("navbar-shrink");
             }
    }

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

The tabs in bootstrap appear to be functioning properly, but the data is not displaying as expected

Currently, I am incorporating Bootstrap into my project and I am attempting to include a Twitter Bootstrap tab. I have already added jQuery and bootstrap-tabs.js to my project. Below is the script that I have added: <script> $('#myTab a&apos ...

Disable button with Checkbox Javascript functionality

In my PHP code, I have an array of users that I pass to the view (in Laravel) and use a foreach loop to display all users in a table. Everything is working fine so far. However, I want to make a "send" button visible when a checkbox is clicked, instead of ...

Tips for making a multiselect dropdown menu using bootstrap

I am working on a JavaScript application that parses data and displays it to users in a table generated by JavaScript. I am looking for a simple way to allow users to choose which fields to display in the table using a dropdown list or something similar. I ...

Trigger a click event on a third-party webpage that is embedded within an Angular application

In the process of developing my angular application, I found a need to incorporate a graph visualization tool. To achieve this, I utilized the HTML <embed> tag and successfully integrated the graph into my application. Now, my objective is to enable ...

What is the effect of SEO on the use of image width and height attributes for a responsive website

Is it true that setting inline width and height for all images is beneficial for SEO and can improve site loading speed? Here's an example: <img src="http://www.example.com/images/free-size.jpg" width="200" height="400" alt="random image" /> E ...

Can text automatically adjust its size based on the browser's dimensions using CSS?

Can text automatically resize as the browser size decreases for liquid-based design using percentages? While images and divs can rescale, text scaling in percentages seems impossible! When set in percentages, it only changes the unified em setting for tha ...

Error in JQuery Document Ready AJAX function causing image to not load initially without a page refresh

Currently, I have a piece of customized code that extracts data from an XML file and uses this data to populate specific content on my webpage: $(document).ready(function() { $.ajax({ type: 'GET', url: 'config.xml?date=& ...

Move your cursor over the image to see a different image appear

I am facing an issue - I'm attempting to make image hover affect another hover <img id="1" src="#" /> <img id="2" src="#" /> #1 {width:20%; opacity:0.5 } #2 {width:80%; position:absolute; display:none; } I have experi ...

Utilizing Angular to import an SVG file from a backend and incorporate its content as a template

I am looking for a solution to load an SVG date from my Spring Boot backend and utilize it as an Angular template. Currently, the request is structured like this: getSVG (): Observable <any> { return this.http.get(`${environment.apiUrl}/path ...

Setting radio buttons as active dynamically can be achieved using jQuery Mobile

Currently, I am utilizing jQuery mobile's horizontal control group for radio buttons. I am facing an issue with setting the first radio button as active. Below are the two radio buttons: <input type="radio" name="rating" id="radio-mini-1" value=" ...

Apply a unique CSS class to the first two elements, then skip the following two elements, and continue this pattern using ngFor in Angular and flex styling

Here is a code snippet that displays a list of products using *ngFor in Angular: <div class="container-products"> <div class="item-product" *ngFor="let product of ['product A', 'product B', 'prod ...

I need to find a way to transfer user input data from the frontend to ExpressJS in order to make an API call using an endpoint

Within my perspective, there is a text box where users can input values. Leveraging jquery, I retrieved the user's value and now aim to transfer it from my jquery file to the express module in app.js. Any ideas on how to best approach this? ...

"Showcasing a pair of icons side by side in an HTML layout

I need assistance with formatting two legends on the form. I want both legends to be displayed side by side instead of one on top of the other. Here's how I want it: -----legendOne---LegendTwo----- What CSS code do I use to achieve this layout? Be ...

Incorporating HTML5 transitions into your website

After researching HTML5 transitions and adapting some examples, I finally achieved the desired effect. <!DOCTYPE html> <html> <head> <style> div { width: 50px; height: 50px; } div. ...

What is the best method for displaying a view on a new page in Angular 2?

Currently, I am facing a challenge with my Angular 2 project. I am struggling to figure out how to make a route open a new view instead of simply rendering in the same page. My goal is for the route to lead to a completely separate view rather than stayi ...

Error encountered while attempting to utilize 'load' in the fetch function of a layer

I've been exploring ways to implement some pre-update logic for a layer, and I believe the fetch method within the layer's props could be the key. Initially, my aim is to understand the default behavior before incorporating custom logic, but I&ap ...

What is the best way to place a floating elastic div on top of an elastic background and ensure that the div stays in place?

Looking for some creative input here. Don't have a specific question in mind, but open to ideas. Just to clarify, I want both the floating div and the background to resize as the window size changes, while keeping the div in the same position on top ...

Expanding the box width to fill the entire space within a Bootstrap 4 card

I am working with Bootstrap code and I have encountered an issue within a card element. There seems to be extra space on the left and right side of the card, which I would like to eliminate so that the content fits within the main card itself. <link ...

What is the process for implementing a third-party component in my web application?

After some experimentation, I've discovered that it's necessary to include the link to the css files in the header and then mention the link to the js files before the closing tag. However, I encountered difficulties when trying to use a compone ...

Image Filter: Only Display Selected Images, Not All

I have designed a Filter Image Gallery where all images are initially displayed when the page loads. There are four different tabs available - Show all, Nature, Cars, and People. However, I want to change this default behavior so that only Nature filter i ...