开发者

Handling clicks outside an element without jquery

开发者 https://www.devze.com 2023-01-28 18:47 出处:网络
I would like to implement the solution 开发者_StackOverflow中文版like this How do I detect a click outside an element?

I would like to implement the solution 开发者_StackOverflow中文版like this

How do I detect a click outside an element?

but I'm using another javascript library with $() function already defined

Any suggestions?


This is easy to accomplish. 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.net/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.com/Using_jQuery_with_Other_Libraries


I also add here the code that stops event bubbling up. Found on quircksmode.org

 function doSomething(e) {
    if (!e) var e = window.event
    // handle event
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
 } 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号