Skip to content

Instantly share code, notes, and snippets.

@jimthoburn
Created September 11, 2013 22:18
Show Gist options
  • Save jimthoburn/6530562 to your computer and use it in GitHub Desktop.
Save jimthoburn/6530562 to your computer and use it in GitHub Desktop.
A JavaScript function that will tell you if an element is within another element. This is useful for things like closing a widget when a user clicks somewhere else in the page.
function within(needle, haystack) {
// If the parent element is the target
if (needle === haystack) {
return true;
// If any of the children are the target
} else if (haystack.firstChild) {
var child = haystack.firstChild;
do {
if (within(needle, child)) return true;
} while(child = child.nextSibling);
}
}
if (within(a, b)) alert(a + " is within " + b);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment