JavaScript

Small But Useful Functions. Part 2

Continuing the series of small but useful JavaScript utility functions. Here are a few more I find myself reaching for regularly.

1. Random integer in a range:

function randomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Usage: randomInt(1, 100) => 42

2. Get mouse cursor coordinates:

function getMouseCoords(e) {
    e = e || window.event;
    return {
        x: e.pageX || e.clientX + document.body.scrollLeft,
        y: e.pageY || e.clientY + document.body.scrollTop
    };
}
document.onmousemove = function(e) {
    var coords = getMouseCoords(e);
    // coords.x, coords.y
};

3. Disable text selection (pure JavaScript, no jQuery):

function disableSelection(el) {
    el.onselectstart = function() { return false; };
    el.unselectable = 'on';
    el.style.MozUserSelect = 'none';
    el.style.cursor = 'default';
}

4. Find the nearest parent matching a selector:

function getParentByClass(el, className) {
    while (el && el.parentNode) {
        el = el.parentNode;
        if (el.className && el.className.indexOf(className) !== -1) {
            return el;
        }
    }
    return null;
}

These functions work across all major browsers of the era, including IE6+. See Part 1 for more utility functions.