I’m having problems with Jquery scroll

Asked

Viewed 40 times

-2

Hello, I am using the scroll function you have in Jquery’s Document, everything goes very well, at least while I am in the component that has the href to scroll, but when I exit this component, I get the following error every time I scroll: ERROR Typeerror: Cannot read Property 'top' of Undefined

Part of the Navbar

export class NavbarComponent implements OnInit {

  // Navbar
  opacityNavbar: number = 0;

  constructor() { }

  ngOnInit() {
    this.animateScrolling();
    this.activeOpacityNavbar();
    this.activeNavbar();
  }

  onNavbar() {
    $('.navbar-collapse').collapse('toggle');
  }

  animateScrolling() {
    $("a").on('click', function () {
      let select = $(this).attr("href");
      let positionAux = $(select).offset().top;
      let position: number;
      if (select == "#home") {
        position = 0;
      } else if (select == "#about") {
        position = positionAux - 73;
      } else if (select == "#services") {
        position = positionAux + 127;
      } else if (select == "#contact") {
        position = positionAux - 43;
      }
      $("html, body").animate({ scrollTop: position }, 600);
    });
  }

  activeNavbar() {
    $(document).scroll(function () {
      var opacityNavbar = $(this).scrollTop();
      if (opacityNavbar >= ($("#home").offset().top) && opacityNavbar < ($("#about").offset().top) - 73) {
        $(".home-nav").addClass("active");
        $(".about-nav").removeClass("active");
        $(".services-nav").removeClass("active");
        $(".contact-nav").removeClass("active");
      } else if (opacityNavbar >= ($("#about").offset().top) - 80 && opacityNavbar < ($("#services").offset().top) + 127) {
        $(".home-nav").removeClass("active");
        $(".about-nav").addClass("active");
        $(".services-nav").removeClass("active");
        $(".contact-nav").removeClass("active");
      } else if (opacityNavbar > ($("#services").offset().top) + 126 && opacityNavbar < ($("#contact").offset().top) - 44) {
        $(".home-nav").removeClass("active");
        $(".about-nav").removeClass("active");
        $(".services-nav").addClass("active");
        $(".contact-nav").removeClass("active");
      } else if (opacityNavbar >= ($("#contact").offset().top) - 43) {
        $(".home-nav").removeClass("active");
        $(".about-nav").removeClass("active");
        $(".services-nav").removeClass("active");
        $(".contact-nav").addClass("active");
      }
    });
  }

  activeOpacityNavbar() {
    $(document).scroll(function () {
      var opacityNavbar = $(this).scrollTop();
      if (opacityNavbar > ($("#about").offset().top) - 40) {
        $(".navbar").addClass("opacity-navbar");
      } else {
        $(".navbar").removeClass("opacity-navbar");
      }
    });
  }
}

Section component for scrolling

<section id="navbar">
  <app-navbar></app-navbar>
</section>

<section id="home">
  <app-home></app-home>
</section>

<section id="about">
  <app-about-me></app-about-me>
</section>

<section id="skills">
  <app-skills></app-skills>
</section>

<section id="services">
  <app-posts></app-posts>
</section>

<section id="contact">
  <app-contact></app-contact>
</section>

<section>
  <app-footer></app-footer>
</section>
<app-flags></app-flags>

Component that is not part of the sections and where I get the error

<div class="bg font">
<div class="container">
    <div class="row">
        <div class="card blue-card col-6">
            <br><br>
            <i class="fas fa-user-astronaut icon text-center"></i>
            <br><br>
            <h1 class="welcome text-center">SEJA BEM-VINDO <br> AO PAINEL ADMINISTRATIVO</h1>
            <img class="logo" src="src\assets\images\Logo Hunter (sem fundo e branco).png" alt="">
        </div>
        <div class="card pink-card col-6">
            <br><br>
            <i class="fas fa-space-shuttle icon text-center"></i>
            <br><br>
            <form>
                <div class="form-group">
                    <label>USUÁRIO</label>
                    <input [(ngModel)]="email" [ngModelOptions]="{standalone: true}" type="text"
                        class="form-control" id="credential" placeholder="Digite o usuário">
                </div>
                <div class="form-group">
                    <label>SENHA</label>
                    <input [(ngModel)]="password" [ngModelOptions]="{standalone: true}" type="password"
                        class="form-control" id="exampleInputPassword1" placeholder="Digite a senha">
                </div>
                <br><br><br>
                <div *ngIf="loading" class="row">
                    <div class="col-12 text-center">
                        <app-lds-facebook-blue></app-lds-facebook-blue>
                    </div>
                </div>
                <button *ngIf="!loading" [disabled]="email == '' || password == ''" (click)="login()" type="button"
                    class="btn">CONECTAR</button>
            </form>
        </div>
    </div>

    <div class="modal font-black" tabindex="-1" role="dialog" id="errorModal">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Não foi possível fazer log in</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <h6>{{ error }}</h6>
                </div>
            </div>
        </div>
    </div>
</div>

Routes (app-routing.module.ts)

const routes: Routes = [
  {
    path: '',
    component: MainComponent
  }, {
    path: 'login',
    component: LoginComponent
  }, {
    path: 'access-denied',
    component: GuardsErrorComponent
  }, {
    path: 'admin',
    component: AdminMainComponent,
    canActivate: [GuardsService],
    children: [
      { path: '', redirectTo: 'home', pathMatch: 'full' }, {
        path: 'home',
        component: AdminHomeComponent,
        canActivate: [GuardsService]
      }, {
        path: 'about',
        component: AdminAboutComponent,
        canActivate: [GuardsService]
      }, {
        path: 'posts',
        component: AdminProjectsComponent,
        canActivate: [GuardsService]
      },
    ]
  },
  { path: 'home', redirectTo: '', pathMatch: 'full' },
  { path: 'about', redirectTo: '', pathMatch: 'full' },
  { path: 'services', redirectTo: '', pathMatch: 'full' },
  { path: 'contact', redirectTo: '', pathMatch: 'full' },
  { path: '**', component: NotFoundComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes, { useHash: true })],
  exports: [RouterModule]
})

export class AppRoutingModule { }

1 answer

0


I arranged the problem as follows, I created a boolean variable to validate if I was in the component that should scroll or not, it is started as true, because we know I am in the component and when we left the component (using ngOnDestroy) we assign the value false (since we are no longer in the component) and then when we return, we change to true again, follows the solution below:

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

declare let $: any;
var scroll = true;

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.scss']
})

ngOnInit() {
    this.animateScrolling();
    this.activeOpacityNavbar();
    this.activeNavbar();
    this.activeScroll();
  }

ngOnDestroy(): void {
    scroll = false;
  }

activeScroll() { 
    if (scroll == false) {
      scroll = true;
    }
  }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.