Sunday, 15 July 2018

SE - 19 - Difference between ScrollTo and ScrollBy in JavaScript

Both the methods are almost same with a slight difference in functionality . Let's see the syntax of both the scroll commands :

1) Window.scrollTo(x-Pixel, y-pixel);

2) Window.scrollBy(x-Pixel, y-pixel);

Difference :The scrollTo is for absolute scrolling and scrollBy is for relative scrolling. In a nutshell we can say that scrollTo will scroll to the (x-Pixel, y-pixel) position of the entire webpage while ScrollBy will move to the (x-Pixel, y-pixel) of the webpage from the current location of cursor.

Eg: Suppose we are at position (100,100) of the webpage , now

Case 1 : If we use Window.scrollTo(200,200) - The window will scroll to position 200,200 of the webpage in spite of the current position of (100,100). At the end of the execution of this command our position will be (200,200)

Case 2 :  If we use Window.scrollBo(200,200) - The window will scroll relatively from the current location to further 200,200 pixels.. At the end of the execution of this command our position will be (300,300) since we started at (100,100).

No comments:

Post a Comment