JAVASCRIPT

JavaScript Helper Functions

Various helper functions are included on this page. See DOM Helpers to look for document object helpers.

document height

Since browsers handle this calculation differently.

var _height = function() {
    var body = document.body,
        html = document.documentElement;

    // get using highest value
    var height = Math.max(
        body.scrollHeight,
        html.scrollHeight,
        body.offsetHeight,
        html.offsetHeight,
        body.clientHeight,
        html.clientHeight
    );

    return height;
}

filename from path

// get the filename from a path without using regex
var _filename = function(path) {
    return path.split('/').pop();
}

find index by key value

// find index of an object in an array by key and value
var _findIndexOf = function(array, key, value) {
    var i;
    for(i = 0; i < array.length; i++) {
        if(array[i].hasOwnProperty(key) && array[i][key] === value) {
            return i;
        }
    }
    return -1;
}

iframe

//breakout of iframe / frame
function iframed() {
    try {
        return window.self !== window.top;
    } catch (e) {
        return true;
    }
}
if(iframed()) window.top.location.reload(false);

path only, remove filename

// get the path only without using regex
var _path = function(path) {
    return path.substring(0, path.lastIndexOf('/') +1);
}

source

math

/**
 * round to decimal place
 *
 * @param num number to round
 * @param dec number of decimal places to round to
 */
function _round(num, dec) {
    return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
}

orientation change listener

Register an event handler by calling addListener() on the MediaQueryList object named query. The callback function will receive this object as an argument when triggered.

var query = window.matchMedia("(orientation:landscape)");
var toggle = function(query) {
    if (query.matches) {
        console.log('------- LANDSCAPE -------')
    } else {
        console.log('------- PORTRAIT -------')
    }
}
query.addListener(toggle);

// remove as needed
query.removeListener(toggle);

MediaQueryList.addListener() is deprecated. You can add a check as follows if you need to support older browsers, e.g., Safari 13.

if (query?.addEventListener) {
    query.addEventListener(toggle);
} else {
    query.addListener(toggle);
}

resize handler

window.addEventListener("resize", resizeThrottler, false);

var resizeTimeout;
function resizeThrottler() {
    // wait for resizeHandler execution to complete
    if ( !resizeTimeout ) {
        resizeTimeout = setTimeout(function next() {
            resizeTimeout = null;
            resizeHandler();

            // resizeHandler executes at 15fps
        }, 66);
    }
}

function resizeHandler() {
    // handle the resize event
    console.log(window.innerWidth);
}

jQuery and/or lodash resize handler

Handler example using a debounce function. Also works for scroll event.

async function handleEvent(event) {
    switch (event.type) {
        case 'resize':
            // do something
            break;
        case 'scroll':
            // do something
            break;
        default:
            break;
    }
}

function debounce(func, wait, immediate) {
	let timeout;
	return function() {
		let context = this, args = arguments;
		let later = function() {
			timeout = null;
			if (!immediate) func.apply(context, args);
		};
		let callNow = immediate && !timeout;
		clearTimeout(timeout);
		timeout = setTimeout(later, wait);
		if (callNow) func.apply(context, args);
	};
};

// wait 1/2 a second
window.addEventListener('resize', debounce((event) => {
    handleEvent(event);
}, 500, false));

// wait 10 milliseconds
window.addEventListener('scroll', debounce((event) => {
    handleEvent(event);
}, 10, false));

validation

// validate external URL syntax
var _isExternalURL = function(str) {
    var a  = document.createElement('a');
    a.href = str;

    if (!a.host || location.host == a.host)
    {
        return false;
    }
    return true;
}
comments powered by Disqus