Last Updated: February 25, 2016
·
706
· 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.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside