JavaScript - Helper Functions

These are some JavaScript functions I saved here because I couldn’t find an equivalent in Underscore.js or lodash or didn’t need the overhead of the whole library.

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;
}
filename from path
// get the filename from a path without using regex
var _filename = function(path) {
    return path.split('/').pop();
}
path only, remove filename
// get the path only without using regex
var _path = function(path) {
    return path.substring(0, path.lastIndexOf('/') +1);
}

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;
}

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);
}

Misc

//breakout of iframe / frame
function iframed() {
    try {
        return window.self !== window.top;
    } catch (e) {
        return true;
    }
}
if(iframed()) window.top.location.reload(false);
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

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);
Loading Disqus Comments ...
Loading Facebook Comments ...