Ad

Two Separate Events With JQuery Click Function

- 1 answer

I am trying to create a TV simulation where user clicks on the power button and it loads an external HTML file, which is just a video (wrapped inside of a DIV for styling purposes and such) into a TV-image (which is a div with a tv image as the background, to make it look like someone is turning on and watching TV). However, I want to also have the user be able to turn the TV off. Currently I have it successfully where it loads the external html file (which contains the video) when the power button is pressed. I'm needing to know how do I create a "turn off" feature for the same button, and not have that button repeat the "turn ON" function.

I'm guessing I have to make two functions with the button that when turned on will also load a div overlaid ontop of the power button, which will then serve as the element to be clicked to turn OFF the TV with a separate jquery or JS fucntion? Since if I hit the power button again it will just repeat the turn on function?

I'm really looking for the theory so I can know what and how I have to do it, but here is the current jQuery that is turning the TV on.

$("#switch").on("click",function(){
    $("#broadcast").load("shows.html");
});

It is important that the user thinks that the power button is turning the TV on and off, even if some overlay or invisible element is placed on top of the power button by virtue of the first/initial onclick.

Ad

Answer

You could simply use a variable to store the "state" of whether the tv is on or not:

var tvOn = false;
$("#switch").on("click", function () { 
    var $el = $('#broadcast');

    if (tvOn) {
        $el.empty();
    }
    else {
        $el.load("shows.html");
    }

    tvOn = !tvOn;
});

Or, if the shows.html file is static content, you could load it once to begin with then show/hide the container when the button is clicked:

var $el = $('#broadcast');
$el.load("shows.html");

$("#switch").on("click", function () {
    $el.toggle();
});
Ad
source: stackoverflow.com
Ad