5

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.

3 Answers 3

9

Looking to the code of jQuery (I looked at 1.7, but I think it is available before that as well) it is easy to create a jQuery Event from a native event using:

var jQueryEvent = jQuery.Event(event);
1
8

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);
};
2
  • 2
    I guess someone didn't like the suggestion that you can do JavaScript without jQuery.
    – Tim Down
    Apr 23, 2013 at 23:10
  • 1
    @Shaheer: There is one (4 up, 1 down). It really doesn't bother me, I just found it curious.
    – Tim Down
    Apr 24, 2013 at 8:43
0

You can remove onclick or whatever inline eventhandler attributes with jQuery right after page load eg.:

$(document).ready(function () {

  $('#someInput').removeAttr('onclick');

});

Then attach Your event handlers to customize behaviour.

1
  • how would i get the parameters passed to it there are two total ?
    – Shaheer
    Dec 19, 2010 at 11:25

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.