Skip to content

Instantly share code, notes, and snippets.

@xuandinhgl
Created September 30, 2020 03:03
Show Gist options
  • Save xuandinhgl/c8ec43b70aeafaf2ea6926e3ee8dbdf0 to your computer and use it in GitHub Desktop.
Save xuandinhgl/c8ec43b70aeafaf2ea6926e3ee8dbdf0 to your computer and use it in GitHub Desktop.
/**
* hide all elements specified
* @example
* hideElement(document.querySelectorAll('img')); // Hides all <img> elements on the page
* @param {...any} el
*/
const hideElement = (...el) =>
[...el].forEach((e) => (e.style.display = "none"));
/**
* check if the element has the specified class
* @param {DOM} el
* @param {string} className
* @returns {boolean}
*/
const hasClass = (el, className) => el.classList.contains(className);
/**
* toggle a class for an element
* @param {DOM} el
* @param {string} className
*/
const toggleClass = (el, className) => el.classList.toggle(className);
/**
*
* @param {DOM} el
* @returns {object}
*/
const getScrollPosition = (el = window) => ({
x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop,
});
/**
* smooth-scroll to the top of the page
*/
const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
};
/**
* check if the parent element contains the child element
* @param {DOM} parent
* @param {DOM} child
* @returns {boolean}
*/
const elementContains = (parent, child) =>
parent !== child && parent.contains(child);
/**
* check if the element specified is visible in the viewport
* @param {DOM} el
* @param {boolean} partiallyVisible
*/
const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
const { top, left, bottom, right } = el.getBoundingClientRect();
const { innerHeight, innerWidth } = window;
return partiallyVisible
? ((top > 0 && top < innerHeight) ||
(bottom > 0 && bottom < innerHeight)) &&
((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
: top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
};
/**
* get URL parameters
* @param {string} url
*/
const getURLParameters = (url) =>
(url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
(a, v) => (
(a[v.slice(0, v.indexOf("="))] = v.slice(v.indexOf("=") + 1)), a
),
{}
);
export {
getURLParameters,
elementContains,
elementIsVisibleInViewport,
scrollToTop,
getScrollPosition,
toggleClass,
hasClass,
hideElement,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment