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?

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
    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
    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
    Dec 1, 2010 at 21:33

3 Answers 3

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');
    };
};
3

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

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();
 } 
2
  • 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 3, 2010 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 3, 2010 at 20:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.