Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a JQuery click handler that executes before the ones already registered

I want to attach a click event handler to each and every (Button, Anchor, Select) on all pages in my application, and that handler should run before the already attached handlers declared in html like onclick="return SomeFunction('a','b');".

I found a question on stackoverflow for prepending handlers, and that was what I wanted exactly, the link to the question is:-

Jquery prepend click handler

But, the above code is not working, I doubt if it worked for the asker or not. The code I have written according to my requirements is:-

<input type="button" value="Click 1" onclick="f2();" />

$(document).ready(function() {
            $("input[type=button]").each(function() {

                // your button
                var btn = $(this);

                // original click handler
                var clickhandler = btn.attr("onclick");
                btn.attr("onclick", "return false;");


                // new click handler
                btn.click(function() {
                    alert('Prepended Handler');
                    clickhandler();
                });
            });
        });

        function f2() {
            alert('Handler declared in HTML');
        }

The output for this code should have been: An alert showing "Prepended Handler" and then a next alert showing "Handler declared in HTML".

But, the actual result is: Only the first alert is appearing and the second one is not.

Please tell me if you see any problem in this code.

And, how can this be done. ?

like image 348
teenup Avatar asked Feb 24 '23 08:02

teenup


1 Answers

This should rearrange your click handlers.

$(document).ready(function() {
    $("input[type=button]").each(function() {

        // your button
        var btn = $(this);

        var clickhandler = this.onclick;
        this.onclick = null;


        // new click handler
        btn.click(function() {
            alert('Prepended Handler');
        });
        btn.click(clickhandler);
    });
});

function f2() {
alert('Handler declared in HTML');
}
like image 129
Kyle Avatar answered Feb 25 '23 21:02

Kyle