views:

34

answers:

1

Dear experts,

I would like to implement a API of Javascript that sort of resemble a light switch.

For instance, there are two buttons on the actual HTML page act as the UI.

Both of the buttons have event handlers that invokes a different function.

Each function have codes that act like a state, for instance.

button1.onclick=function (){
   $("div").click(
        //code effects 2
   )
}

button2.onclick=function (){
   $("div").click(
        //Code effects 2
   )
}

I the code works fine on the surface but the 2 state functions overlap.

the effects is going to take place for the rest of the way until the next reload of the document.

Basically what I want to achieve is that when 1 button is clicked, it will switch "OFF" the state of function invoked by the other button and vice versa.

Thus, the effects achieved are unique are not overlapped.

Is there anyway to achieve this or could any experts point me to the right direction.

Thanks in advance.

+1  A: 

To do this you simply need a place to store the 'state'. You could simply store the on/off information in a cookie. Each javascript function could then check and/or update the value in the cookie.

On page load you could set the initial state in the cookie to whatever you want (on/off)

Using jQuery, sample:

$(document).ready(function(){

    //set cookie to OFF state during initial load

    //add event handler for On button
    $('#buttonOn').click(function(){
        //set cookie to ON
    });

    //add event handler for Off button
    $('#buttonOff').click(function(){
        //set cookie to OFF
    });

});

jQuery has many plugins for cookie support. Best one I've used is: http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/

KP
other than cookie is there a way via javascript that can somehow cancel out a function block itself?Sort of like reversing the effect if possible?
Dennis D
Essentially what you're asking though is a 2-state mechanism. To do this the easiest way is to store the state info 'somewhere'. Cookies would work. Another option is in a hidden field. Hidden field may work well because you don't have to worry about the browser blocking cookies (pretty rare but possible)..
KP
Why are we complicating things using cookies? Just a simple variable will work!?
Matt
@Matt fair enough.. was originally thinking cross-page support but might be overkill.
KP