I would like to implement the solution like this
How do I detect a click outside an element?
but I'm using another javascript library with $() function already defined
Any suggestions?
I would like to implement the solution like this
How do I detect a click outside an element?
but I'm using another javascript library with $() function already defined
Any suggestions?
Share Improve this question edited May 23, 2017 at 11:55 CommunityBot 11 silver badge asked Dec 1, 2010 at 1:54 DanDan 58k44 gold badges122 silver badges162 bronze badges 3- What is the other library? Why don't you just use that, or a non-library solution. I wouldn't load another library just for one feature. – user113716 Commented Dec 1, 2010 at 2:40
- @patrick. Yes, I load jquery only to launch "outside click" feature. I haven't found any standalone code within 20 minutes of googling. On ly big library solutions. – Dan Commented Dec 1, 2010 at 21:04
-
In that case, I'll add an answer using a native solution. If your other library has methods for adding
click
handlers, then you could do it with that library too. See my answer below. – user113716 Commented Dec 1, 2010 at 21:33
3 Answers
Reset to default 6This is easy to acplish. Would be a shame to load the jQuery library just for one feature.
If the other library you're using handles event binding, you could do the same thing in that library. Since you didn't indicate what that other library is, here's a native solution:
Example: http://jsfiddle/patrick_dw/wWkJR/1/
window.onload = function() {
// For clicks inside the element
document.getElementById('myElement').onclick = function(e) {
// Make sure the event doesn't bubble from your element
if (e) { e.stopPropagation(); }
else { window.event.cancelBubble = true; }
// Place the code for this element here
alert('this was a click inside');
};
// For clicks elsewhere on the page
document.onclick = function() {
alert('this was a click outside');
};
};
If the $
conflict is your only hold-up, there are ways around that:
http://docs.jquery./Using_jQuery_with_Other_Libraries
I also add here the code that stops event bubbling up. Found on quircksmode
function doSomething(e) {
if (!e) var e = window.event
// handle event
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
}