TIL
A lot of my recent JavaScript related TIL posts have been based on a Udemy course that I am currently taking, in addition to notes that I took while I did additional MDN readings corresponding to the course content.
-
To access data-attributes of a DOM node, you can use
element.dataset
-
element.getBoundingClientRect()
- returnsDOMRect
object with info about element’s size and position relative to the viewport -
in order to understand the coordinates/values that the
DOMRect
returns, you have to understand that the (0,0) - the origin for a webpage starts at the top left corner. MDN actually has a great [diagram(https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect/element-box-diagram.png) that made my understanding a lot easier. -
element.scrollHeight
- tells you the entire height of the element that is scrollable (even if part of the scrollable content is hidden, this property tells you the total height)element.scrollTop
- tells you how much of that element you have scrolled down or up.
“Scroll” related Browser APIs:
- If you want to have an element be at a particular absolute scrolling position (e.g. maybe you want the middle part of the scrollable content to be shown) ->
element.scrollTo(x,y)
. - if you want the content to scroll down relative to its current position, you can use
Element.scrollBy(x,y)
. - If you want to scroll the element’s ancestor so that the particular element is within the viewport ->
element.scrollIntoView()
** technically you can also pass in other options as arguments for these methods (e.g. if you want smooth scrolling, you canelement.scrollIntoView({behavior: 'smooth'});