Created
September 11, 2013 22:18
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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