Skip to content
Advertisement

Converting a native js event object to jQuery event object

I want to convert a native JavaScript event object to jQuery event object.

Actually this is the problem:
I have bound an event handler to documents keyup event via jQuery and there are some text boxes on the page with which a keyup event handler is bound via inline JavaScript.

The problem is when the text box’s event handler is fired the document’s event handler also gets fired because the event “bubbles up” I can modify the event handler function bound by inline JavaScript but not that line itself.

What I am looking for is a cross browser, a way to cancel the event bubbling that’s why I wanted to convert it to a jQuery object.

Advertisement

Answer

If all you want to do is prevent an event from bubbling, that’s easy without jQuery. Don’t be scared of stepping outside the world of jQuery. It’s not as complicated as some people would have you believe.

function stopEventPropagation(evt) {
    if (typeof evt.stopPropagation != "undefined") {
        evt.stopPropagation();
    } else {
        evt.cancelBubble = true;
    }
}

// Example
document.getElementById("yourInputId").onkeyup = function(evt) {
    evt = evt || window.event;
    stopEventPropagation(evt);
};
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement