blog about graphic design, web design and marketing

The D. Drew Design Blog
25
jun 11

jQuery is-or-is-child-of function

Sometimes, in Javascript, when you interact with an element, you want to know if that element is or is the child of a specific element. A case of this might be a context menu that you have pop-up when you click on elements on the page, but you want it to be smart enough not to re-propogate when you click on the context menu itself.

For the purposes of this example, simply checking if the element is the child of your context menu with .parents().size() is not sufficient, because if you happen to miss the element's area and click on the container itself, it will not react favorably. Likewise, if you are only checking if the element is the context menu in question with something like .is(), most times you will get a false positive, as the element you're click on doesn't recognize itself by the selector you're using in the .is() statement.

This is a super tiny function you can use to determine if the element you're interacting with has anything to do with the selector in question:


$.fn.isOf = function( selector ){
    if( $(this).is(selector) || $(this).parents(selector).size() > 0 ){
        return true;
    }
    return false;
}


I call it .isOf() and you use it by sending the target element and the selector in question to it. Let's say you wanted to check before executing code if the element you just clicked on "was of" the div with the id of context-menu. If it isn't you want the code to execute:


$('html').click( function(e){
    if( !$(e.target).isOf('#context-menu') ){
        // More code
    }
});


Super simple! Hope you can find use in this. As always, if you have any questions, don't hesitate to hit me up.

Tags: jquery, code, freeware, plugin, javascript


Some other articles you might enjoy...