Jquery prepend click handler

John picture John · Aug 12, 2009 · Viewed 8k times · Source

If you know a better way to do this then please let me know. Right I have a page which will contain lots of buttons, charts and tables. I have read about stopping event propogation and that's what I'll be using. I want to enable help on cerain elements. I have a checkbox which changes the cursor on help enabled divs. What I want to do is prepend a help function before the normal click behaviour.

Basically it's like this.

<input type="button" value="Click me" onclick="alert ('hello')" />

what i want is that if the checkbox is clicked I add a css class (already done) and then I add a click handler before the normal click. When the element is clicked then the helpfunction is run and the default button click handler is not fired. When the help checkbox is unchecked I want to remove the help function. I realise that I could hardocde this for each element and have a check in the helperfunction to see if the checkbox is checked. But I'd prefer a more generic way of doing it.

Thanks

John

Answer

Anwar Chandra picture Anwar Chandra · Aug 12, 2009
        $(":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() {

                if ($("#chkbox").attr("checked") == true) {

                    // TODO: show your help
                    // TODO: catch event

                }
                else {

                    clickhandler();

                }
            });
        });