0

Note: I now about event bubling and how to stop it.

Code ==>

function foo ( bar ){
//do something
}

In the above function,i want to capture the event so I can stop it from bubling out.

What i've tried so far -->

Try 1

function foo ( bar,event ){
//do something
}

Try 2

function foo (bar ){
if( window.event || event )
   // code to stop bubling

//do something
}

Not using jQuery, vanilla js solution required. Using this method for prevention of event bubling.

-- beginner.

1
  • 1
    Where is the event coming from?
    – Eric
    Oct 24, 2012 at 6:50

2 Answers 2

1

Try:

function foo ( bar,event ){
  if (event.stopPropagation) {
    event.stopPropagation();
  } else {
    event.cancelBubble = true;
  } 
}
1
  • Tried it,dint work - please read the question - i've already mentioned that i've tried it!! Oct 24, 2012 at 6:51
0
elem.onclick = function(e) {
    e = e || window.event;
    if (e.stopPropagation) {
        e.stopPropagation();
    } else {
        e.cancelBubble = true;
    }
};

http://jsfiddle.net/WnSjb/

2
  • I know how to stop it, i've also given a reference to the method on how to stop event bubling. You have to have the object event or window.event to send stop it from bubling. I want to capture that!!. Oct 24, 2012 at 6:55
  • 1
    @VivekChandra Well your original code has a few mistakes I fixed.. first of all, you are just defining a function - not adding an event listener. Secondly, the event object is sent as the first argument to the function. So, if you have .onclick = function( bar, event ) {}, bar will be the event object if the argument is sent. The rest is undefined because only one argument is passed.
    – Esailija
    Oct 24, 2012 at 7: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.