Search code examples
javascriptparametersevent-bubbling

Is there a way stop bubble in javascript without "e" parameter?


I have see a lot tutorial that tell me the way to prevent bubble is use "e" parameter

just like :

function(e){
    e.preventDefault()
}

but in some situation,the firebug tell me it is wrong with "e is not define"

so is there a way to stop the bubble without the parameter e?


Solution

  • If you set an event handler by using an element attribute (say, <button onclick="myFunc()">) the argument list will be empty. You have to use <button onclick="myFunc(event)"> instead to pass the current event as an argument. No argument will be passed to the callback function by default.

    event is a special variable in this case. When using <element onEVENT="code"> the browser creates a new script and a function with the FunctionBody "code". This function will then take one argument event, thus you can use this object in your own function/code (see w3c:ehca). Note that IE creates a global object event for every triggered event.

    So pass event as an additional variable and use e.preventDefault() and e.stopPropagation. Note that return false; won't cancel the propagation in a click event.

    Demonstrations:

    References: