views:

715

answers:

2

Hi, 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

A: 

I think you want to play around with bind/unbind in this case - see http://docs.jquery.com/Events/unbind#typefn

when selecting the checkbox you can bind new click events on your buttons - and unbind them later on.

You will probably also have to work with Event.preventDefault (http://docs.jquery.com/Events/jQuery.Event) in order to suppress the default click behavior if you dont want it

You would use something the likes of:

$("a").bind("click", function(event){
 if ($("#helpcheckbox").attr('checked')
 {
  event.preventDefault();
  // do something
 }
});

Without more code it's hard to be more exact.

Niko
+2  A: 
        $(":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();

                }
            });
        });
Anwar Chandra
excellent, exactly what I needed thanks
JD
thanks for simplifying some existing code of mine.
NTulip