3

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?

Community
  • 1
  • 1
Dan
  • 55,715
  • 40
  • 116
  • 154
  • 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 Dec 01 '10 at 02: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 Dec 01 '10 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 Dec 01 '10 at 21:33

3 Answers3

6

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');
    };
};
user113716
  • 318,772
  • 63
  • 451
  • 440
3

If the $ conflict is your only hold-up, there are ways around that: http://docs.jquery.com/Using_jQuery_with_Other_Libraries

Emmett
  • 14,035
  • 12
  • 56
  • 81
0

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();
 } 
Dan
  • 55,715
  • 40
  • 116
  • 154
  • This script seems to be the exact copy of the solution given by patrick dw. I'll delete my post if it's true. Is it? – Dan Dec 03 '10 at 19:31
  • Dan - Basically the same. This is simply a cross-browser solution for preventing an event from bubbling. IE uses `window.event.cancelBubble` while W3C compliant browsers use `e.stopPropagation()`. This is what prevents the event inside your element from bubbling up to the handler placed on the `document` in my answer. – user113716 Dec 03 '10 at 20:00