admin管理员组文章数量:1388822
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();
}
本文标签: javascriptHandling clicks outside an element without jqueryStack Overflow
版权声明:本文标题:javascript - Handling clicks outside an element without jquery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744589835a2614418.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论