Search code examples
javascriptdom-events

What is the effect of `return false;` on Custom Events?


Similar to this question about jQuery custom events, I'm trying to find out what the effect of return false; is, with the exception that I am not using jQuery. I'm triggering a custom event via the following method:

var event = document.createEvent('Event');
event.initEvent('CustomName', false, true);
element.dispatchEvent(event);

This is wrapped in a function, and I return the event object after dispatching the event. Now, I'm looking for a way in the triggering code to see if one of the listeners returned false so that I can prevent further execution. How would I be able to detect if one of the listeners returned false in a cross-browser manner (IE 7+)?


Solution

  • It specifies if the created event will bubble through or not

    (EDIT) consider the following example:

    var evt = document.createEvent('Event');
    evt.initEvent('myevent', true, true); // the third argument here specifies whether the event can be cancelled
    var elem = document.getElementById('mydiv');
    elem.addEventListener('myevent', function(e){
        e.preventDefault();
    }, true);
    console.log(elem.dispatchEvent(evt)); //Here you will get return value of false because in the event handler you called e.preventDefault()
    

    The problem is that you want it to work with IE 7+ but IE 7 and 8 don't support document.createEvent in the first place