Search code examples
jqueryjquery-uisyntaxjquery-eventsconventions

Why use built in jQuery events


I'm just wondering if someone could point out why one should use jQuery event bindings rather then native JavaScript. A colleague of mine sent me the following code.

document.forms[0].onsubmit = function () {
    if (Page_IsValid) {
        $("#dialog").dialog({
            height: 140,
            modal: true,
            resizable: false,
            title: ''

        });
        $(".ui-dialog-titlebar").hide();
    }
}

And I told him to rewrite it as.

$(".form").submit(function () {
    if (Page_IsValid) {
        $(".dialog").dialog({ 
            height: 140,
            modal: true,
            resizable: false,
            title: '',
            open: function (event, ui) {
                $(".ui-dialog-titlebar").hide();
            }
        });
    }
});

But when queried about why one should use my code I couldnt provide any specific reason other than syntactic clarity and convention. So are there any other reasons one would use the second example over the first? If not, what is the real advantage of using jQuery in this case?


Solution

  • One reason is you don't have to worry about trampling over previously-defined event callbacks. jQuery will queue them up and run all of them.

    note: Your rewritten version will also attach the behavior to anything on the page with a class of form, while the original version attaches to the first form on the page, regardless of its class. This may not be what you want.