views:

107

answers:

3

I have a jQuery tip function. I would like to create a button to turn on and turn off the function. I want it to be on by default.

Is it possible to create a link to turn on and off a function?

A: 

A little more info is needed, but you could use a global variable to toggle an if statement within the function so it doesn't execute anything, but the function will still be called.

Brent D
Unhooking and rehooking is another (less ugly) alternative.
You
+1  A: 

You can set a boolean to check if it's on or off, or bind and unbind a function.

var isOn = false;

$("#button").click(function(){ isOn = !isOn; });

$("#executebutton").click(MyFunction);

function MyFunction()
{
    if (!isOn) return;
    // do stuff
}

or

$("#button").click
(
    function()
    {
        if ($("#executebutton").data("events").click != undefined)
            $("#executebutton").unbind("click");
        else
            $("#executebutton").bind("click", MyFunction);
    }
);
BrunoLM
A: 

You can dynamically add and subtract event handlers with the bind and unbind functions.

$("#id").click( function() {

    if ( HANDLER_IS_SET )
        $("#button").unbind( "click");    
    else       
        $("#button").bind( "click", myEventHandlerFunction );             
}
CrazyJugglerDrummer
I want to use this function: http://code.drewwilson.com/entry/tiptip-jquery-pluginCan I have a checkbox that will turn off the function?
Erik
@Erik yes you can. We won't code it for you though, but we can help if you have any questions. :D
CrazyJugglerDrummer