7

Want to go to top of the page on button click , Currently I using following code which is not working :

HTML:

<button md-raised-button class="md-raised md-primary" (click)="onEdit()">Edit</button>

Function:

onEdit(){
    window.scrollTo(0,0);
  }
GsMalhotra
  • 1,837
  • 3
  • 14
  • 22
  • Did you check http://stackoverflow.com/questions/19311301/how-to-scroll-back-to-the-top-of-page-on-button-click? – eko Dec 28 '16 at 13:33
  • Possible duplicate of [How to scroll back to the top of page on button click?](https://stackoverflow.com/questions/19311301/how-to-scroll-back-to-the-top-of-page-on-button-click) – Code... Oct 26 '19 at 16:06

10 Answers10

10
onEdit(){
    document.body.scrollTop = document.documentElement.scrollTop = 0;
  }
anshuVersatile
  • 2,030
  • 1
  • 11
  • 18
8

This is my solution based partly on the back to top button example of w3schools.

html:

<button (click)="topFunction()" id="myBtn" title="Go to top">Top</button>

CSS:

/*-----------------------------Button-------------------*/

#myBtn {
    display: none; /* Hidden by default */
    position: fixed; /* Fixed/sticky position */
    bottom: 20px; /* Place the button at the bottom of the page */
    right: 30px; /* Place the button 30px from the right */
    z-index: 99; /* Make sure it does not overlap */
    border: none; /* Remove borders */
    outline: none; /* Remove outline */
    background-color: red; /* Set a background color */
    color: white; /* Text color */
    cursor: pointer; /* Add a mouse pointer on hover */
    padding: 15px; /* Some padding */
    border-radius: 10px; /* Rounded corners */
    font-size: 18px; /* Increase font size */
}

#myBtn:hover {
    background-color: #555; /* Add a dark-grey background on hover */
} 

typescript:

  @HostListener("window:scroll", []) onWindowScroll() {
    this.scrollFunction();
  }
  // When the user scrolls down 20px from the top of the document, show the button
scrollFunction() {
    if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
        document.getElementById("myBtn").style.display = "block";
    } else {
        document.getElementById("myBtn").style.display = "none";
    }
}

// When the user clicks on the button, scroll to the top of the document
topFunction() {
    document.body.scrollTop = 0; // For Safari
    document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
} 

Hope it helps anyone

Maurice
  • 6,698
  • 9
  • 47
  • 104
5

The Right way is to use the DOCUMENT DI Token

Import it

import { Component, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

Inject DOCUMENT

constructor(@Inject(DOCUMENT) private dom: Document) {
}

And then you can call

this.dom.body.scrollTop =0;
this.dom.documentElement.scrollTop=0;

This also works in SSR (Angular Universal)

SwissCodeMen
  • 4,222
  • 8
  • 24
  • 34
vcs
  • 3,675
  • 4
  • 17
  • 15
4

I have try below code its working fine :

import { Inject } from '@angular/core';

@Component({
  ...
  providers: [
      { provide: Window, useValue: window }  
  ],
...
})
export class ProgressComponent implements OnInit {
constructor(
    @Inject(Window) private window: Window,
  ) { }

onEdit(){
    this.window.document.getElementById('editSection').scrollIntoView();
  }
}
GsMalhotra
  • 1,837
  • 3
  • 14
  • 22
3

I am using angular 6(this will work on angular 2 as well). Here is my sample code. sample.component.html

<div class="container-fluid row mx-auto px-2 my-2">
    <button type="button" class="btn btn-primary btn-sm" (click)="gotoSection()">Go to Section</button>
    <!-- content -->
</div>
<div class="container-fluid row mx-auto px-2 my-2">
    <!-- any content -->
</div>
<div class="container-fluid row mx-auto px-2 my-2"  #sectionNeedToScroll>
    <!-- any content -->
</div>

sample.component.ts

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

@Component({
    selector: 'app-sample',
    templateUrl: './sample.component.html'
})

export class Sample {
    @ViewChild('sectionNeedToScroll') sectionNeedToScroll: ElementRef

    constructor() { }

    public gotoSection() {
        //this will provide smooth animation for the scroll
        this.sectionNeedToScroll.nativeElement.scrollIntoView({ behavior: 'smooth', block: 'center' })
    }
}
shanakac
  • 101
  • 1
  • 3
2

Just use on click of button

document.body.scrollTop = 0;
Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
1

The new kid on the block ngx-scrolltop

ng add ngx-scrolltop

Small Angular library which solve this problem: https://github.com/bartholomej/ngx-scrolltop

Bartholomej
  • 143
  • 7
0

You can use this code:

Angular

<button md-raised-button class="md-raised md-primary" onclick="onEdit()">Edit</button> // button onclick

JS:

function onEdit() { // function onEdit
window.scrollTo(0, 0); // very top
}
Code...
  • 104
  • 1
  • 11
  • Also in CSS you could add ` scroll-behavior: smooth;` to make it look cool. You don't have to do this, it is just a opinion. – Code... Oct 26 '19 at 16:09
0

Assign an id to the top element. Example

<div class="container">
   <h1 id="top">TOP HERE</h1>
</div>

In your function:

backToTop() {
   document.getElementById('top').scrollIntoView();
}

In your button:

<button (click)="backToTop()">Back to top</button>
EricSchaefer
  • 25,272
  • 21
  • 67
  • 103
0
<!--Scroll to top-->
<div class="scroll-to-top" [ngClass]="{'show-scrollTop': windowScrolled}">
  <button (click)="scrollToTop()">
      <i class="fa fa-chevron-up"></i>
  </button>
</div>



import { Component, OnInit, Inject, HostListener } from '@angular/core';
import { DOCUMENT } from "@angular/platform-browser";
@Component({
    selector: 'app-scroll-top',
    templateUrl: './scroll-top.component.html',
    styleUrls: ['./scroll-top.component.css']
})
export class ScrollTopComponent implements OnInit {
    windowScrolled: boolean;
    constructor(@Inject(DOCUMENT) private document: Document) {}
    @HostListener("window:scroll", [])
    onWindowScroll() {
        if (window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop > 100) {
            this.windowScrolled = true;
        } 
       else if (this.windowScrolled && window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop < 10) {
            this.windowScrolled = false;
        }
    }
    scrollToTop() {
        (function smoothscroll() {
            var currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
            if (currentScroll > 0) {
                window.requestAnimationFrame(smoothscroll);
                window.scrollTo(0, currentScroll - (currentScroll / 8));
            }enter code here
        })();
    }
    ngOnInit() {}
}
Ravat Sindhav
  • 49
  • 2
  • 9