Notes on Day 13 of 30 Days of JavaScript

Table of Contents

Lessons Learned

debounce

The concept of debounce in JavaScript refers to limiting events, usually trigerred by users, to at least once per a given stimulus (say clicks, scroll or typing on a text field).

The following is a simple implementation:

function debounce(func, timeout = 300){
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => { func.apply(this, args); }, timeout);
  };
}

This method wraps a callback func into a timeout and executes it given a time period. It also makes sure that only one timer object exists at a time.

Window.scrollX and Window.scrollY

The read-only scrollX property of the Window interface returns the number of pixels that the document is currently scrolled horizontally. This value is subpixel precise in modern browsers, meaning that it isn’t necessarily a whole number. You can get the number of pixels the document is scrolled vertically from the scrollY property.

const container = document.getElementById('object')
let xPosition = window.scrollX
let yPosition = window.scrollY

if(xPosition > 100 && yPosition < 50) {
  ...
}

HTMLElement.offsetTop

The HTMLElement.offsetTop read-only property returns the distance of the outer border of the current element relative to the inner border of the top of the offsetParent node.

const container = document.getElementById('object')

if(container.offsetTop > 100) {
  ...
}

References

Twitter, LinkedIn