Create a fixed navbar while scrolling in Angular 5

I want to make a change to the menu position so that it becomes fixed when it reaches the top of the page. Here is my approach:

import { Component, OnInit, Inject, HostListener } from '@angular/core';
import {Location} from '@angular/common';
import { DOCUMENT } from "@angular/platform-browser";
....
export class DashboardComponent implements OnInit {
  constructor(private _location: Location, @Inject(DOCUMENT) private doc: Document) { }
  public fixed: boolean = false; 
  @HostListener("window:scroll", [])
  onWindowScroll() {
    let num = this.doc.body.scrollTop;
    console.log("scroll top" , this.doc.body.scrollTop)
    if ( num > 50 ) {
        this.fixed = true;
    } else if (this.fixed && num < 5) {
        this.fixed = false;
    }
  }

In HTML

<div [class.menus]="fixed">
  <div class="left-menu ">
    <app-left-menu></app-left-menu>
  </div>
  <div class="second-menu" >
    <app-second-menu (display)="onDisplay($event)" [expanded]=expanded ></app-second-menu>
  </div>
</div>

CSS

.menus{
  position: fixed;
}

The issue I am facing is that the scrollTop value is not changing. Even when I do

console.log(this.doc.body.scrollTop)
and scroll, the value remains at 0.

Answer №1

It is probable that the body is not functioning as the scroll container, rather it is the HTML element itself

You can attempt using

document.documentElement.scrollTop

In web browsers, the document.documentElement refers to the main root HTML element

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

Implementing tether in webpack: A step-by-step guide

My webpack application, which I am using with Laravel Elixir, includes a 'bootstrap.js' file for initializing all libraries. Here is the content of the file: window._ = require('lodash'); /** * We'll load jQuery and the Bootstra ...

Tips on accessing a specific element that has been mapped in React?

TL;DR - I'm struggling to target and open a specific menu from a list generated using map() on an array without a reference. I've encountered an issue with my React.js code that I need assistance with to resolve. The main concept behind this lo ...

The use of refs on Function components in SVG is not supported. Any attempts to access the ref will result in an

I am currently working on integrating a navigation bar component using an SVG image in Next.js. While attempting to import and utilize the SVG image, I encountered an error that I couldn't resolve. I tried using Emotion JS to create and use the SVG, ...

I am looking to customize the color of my Material UI switch

I am having difficulty changing the color of my Material UI switch based on my preference. I have tried several ways, but have not achieved the desired outcome. const useStyles = makeStyles((theme) => ({ toggle: { '& .Mui-checked': ...

Mars Eclipse, AngularJS and the power of NodeJS

Could you please assist me in understanding the workings of node.js and angular.js within Eclipse? I am using Eclipse Mars and I would like to run my Angularjs project on a local server (localhost:8080) but I am unsure of how to accomplish this. I have a ...

Having trouble with the JavaScript code for a basic GPA calculator?

I am having issues with my code for a basic grade calculator. Even though I can input numbers, the final grade is not displayed on the screen. Can someone please help me identify what mistake I might be making? Please ignore the Japanese text, as it's ...

Angular 10 is displaying a message indicating that a font has not been

I'm facing an error in my Angular project when trying to add a font to the SCSS file. How can I resolve this issue? style.scss: @import "~@angular/material/theming"; @include mat-core(); $PWP-primary: mat-palette($mat-indigo); $PWP-accent: ...

Ways to implement a time delay when adding a mesh to a scene in three.js

I'm trying to incorporate a mesh into the scene with a time delay, but I'm having trouble getting the setTimeout function to work properly. var geometry = new THREE.BoxGeometry(1, 1, 1); var material = new THREE.MeshLambertMaterial({color: 0xFF0 ...

Issues regarding innerHTML

I have a collapsed table with a link that collapses its content. My goal is to change the link (such as from "+" to "-" and vice versa) using JavaScript. I was able to achieve this, but now my table no longer collapses. Here is the code snippet: <div c ...

Tips for determining the return type when a function yields various promise types

A scenario in which a function returns a Promise with two different potential types based on the parameters passed to it: async function myFunction(buf: boolean): Promise<Buffer | string> { const bytes = "00"; if (buf) { ret ...

Guide on implementing the recently established attribute ID using jQuery

In my code snippet, I am assigning a new id to a button. Here is the code: $("#update").click(function(){ $("#update").attr('id', 'cancel'); }); After changing the id, I want to make it functional again in jQuery by reverting it b ...

Puppeteer and Chromium are ready to go with no need for any configuration

I have a specific HTTP request that I am trying to intercept, but I am encountering issues when chromium is launched through puppeteer. Some flags seem to be causing the requests to not return the expected data. However, everything works fine when I manual ...

The functionality of the Ajax form is limited to a single use

Here's how my script is currently looking. Yes, it comes from a plugin. No, I'm not very familiar with ajax. Is there a way for me to make this form refresh and be ready to accept input again after the first submission? <script> jQuery(do ...

Enclosing Functions Within Anonymous Functions - JavaScript

Recently, I've delved into the world of using anonymous JavaScript functions and have a query regarding their usage with event listeners through jQuery. For instance, I have the following event listener that triggers actions upon the submission of a ...

Click on the login button once the field has reached its maximum length

I need assistance with a login form that has a maximum length of 4 characters for both empNum and ssn. Below is the code snippet: <input type="text" id="empNo" name="empNo" style="width: 90px; margin-left: 10px" maxlength="4" onkeyup="nextField(this, & ...

What is the best way to perform a pure JavaScript forEach loop and display the output with Firebase?

I am attempting to retrieve data from a firebase database and display all of the results. I am used to using jquery's appendTo function for this task, but I am unsure how to achieve the same result with pure javascript. Below is my current script: & ...

What steps should I take to fix this TypeScript error?

I've been struggling to fix this error, but I'm unsure of the best way to resolve it. Here is the code snippet I've been working with:https://i.sstatic.net/m6M48.png Here is the specific error message: https://i.sstatic.net/uk6QY.png ...

Utilize only certain JSON properties within JavaScript

I have access to an array of JSON objects. [ { Id: "1", StartNo: "1", ChipNo: "0", CategoryId: "0", Wave: "0", Club: "", FirstName: "Lotta", LastName: "Svenström", FullName: "Lotta Svenström", ZipCode: "24231" }, {...} ] My goal is to create a new data ...

Utilizing jQuery to assign a value to a SPAN tag

In my code, there is an element with the following syntax: <span id="userName.errors" class="errors">Enter Your User Name </span>. I am interested in utilizing jQuery to delete either the text 'Enter Your User Name' or any element tha ...

Showing different HTML elements based on the link that is clicked

Recently, I delved into the world of web development and decided to test my skills by creating a basic webpage with an interactive top navigation bar. Depending on the link clicked, specific HTML elements would be displayed while turning off others using a ...