Last Updated: February 25, 2016
·
484
· darklg

Ensure a function is only executed one time on an element

This code shows how to avoid two executions of a function on an single element. Moreover, the CSS class allows us to confirm the launch of this function.

function set_element(el) {
    var testClass = 'has-func-set-element';
    if (el.hasClass(testClass)) {
        return false;
    }
    el.addClass(testClass);

    // el.children('.child').each(function())
    return true;
}

set_element($('test'));
// Returns true

set_element($('test'));
// Returns false

This code can be used in MooTools or jQuery.