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...
| Fixing the 100% width text input field | Friday, July 1, 2011 |
| Snazzy jQuery Form Alert Boxes | Tuesday, February 9, 2010 |
| jQuery Vertical Align Function | Wednesday, October 27, 2010 |
| E-mail Newsletter Form with jQuery, AJAX, MySQL and PHP | Sunday, March 14, 2010 |
| Creating An Image Management System for Your Website with Smart Image Resizer and Lightbox 2 | Saturday, July 11, 2009 |
design 16 articles
user interface 7 articles
php 7 articles
code 7 articles
web 6 articles
jquery 6 articles
tutorial 6 articles
picture 5 articles
marketing 5 articles
html 4 articles
2012
2011
2010
2009