Skip to content

Instantly share code, notes, and snippets.

@EmielZuurbier
EmielZuurbier / getElementsInView.js
Created August 18, 2021 08:12
Detect elements in viewports. Uses the Intersection Observer API to async detect elements.
/**
* Returns an array of elements that are currently in view.
* @param {string} selector A CSS selector to query elements.
* @param {boolean} partially Detect elements that are partially in view. Otherwise they would have to be fully in view.
* @returns {Promise<HTMLElement[]>}
*/
const getElementsInView = (selector = '*', partially = true) =>
new Promise(resolve => {
const elements = document.querySelectorAll(selector)
@EmielZuurbier
EmielZuurbier / lazy.js
Created February 10, 2020 18:27
Lazy loading function to load img, picture, audio or video, and background images.
/**
* Checks if an image has a data-src or data-srcset attribute
* and returns the answer in a Promise.
*
* @param {HTMLImageElement} image The image to check
* @returns {boolean} True when data attributes are present, false when not.
*/
export const isImageLazyLoadable = image =>
image.getAttribute('data-src') !== null || image.getAttribute('data-srcset' !== null);
@EmielZuurbier
EmielZuurbier / template.js
Last active February 6, 2020 15:35
Wrapper for creating a reusable template string based on a callback. Provides ability to render and re-render the template, and insert a clone of the template anywhere in the document.
/**
* Wrapper for creating a reusable template string based on a callback given
* by the user. The template string will be wrapped in a <template> element to
* clone the instance of the rendered template.
*/
class Template {
/**
* Rendered string of template.
*
@EmielZuurbier
EmielZuurbier / private-instance-field.js
Last active January 14, 2020 01:37
Private instance field of JavaScript of a class example.
/**
* Not precisely a "read-only" property but it can (in the near future) behave as one with
* ES2019 spec private instance fields. With a single get method and a "private instance field"
* it is possible to simulate the effect, like the examples above, with the added bonus of having
* the private property truly hidden.
*
* Although MDN is not the ultimate authority, their examples don't show the necessity to have a `setter`
* with a `getter`. Making having only a `getter` already a case of having a "read-only" value.
*
* @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Class_fields