Behseini
Behseini

Reputation: 6320

Toggling Between Two Divs by One Click Button

I am having trouble on toggling two elements(divs) with button click event. I have a demo here

My code is like this :

<div id="green"></div>
<div id="red"></div>
<button>Call Red</button>
<script>
$(document).ready(function(){
 $("button").click(function () {
  $("#green").show();
  $("#red").hide();
 });
});
</script>

and css looks like:

#red {
    border:1px solid black;
    width:50px;
    height:50px;
    background-color:red;
}
#green {
    border:1px solid black;
    width:50px;
    height:50px;
    background-color:green;
    display:none;
}

What I need is having a Toggle function to change visibilty between two divs and change the value of button based on next color. Can you please tell me how to do that?

Upvotes: 1

Views: 3652

Answers (2)

Irfan TahirKheli
Irfan TahirKheli

Reputation: 3662

Change:

 $("#green").show();
  $("#red").hide();

To:

 $("#green").toggle();
  $("#red").toggle();

Upvotes: 0

Venkata Krishna
Venkata Krishna

Reputation: 15112

function ButtonText() {
    if ($("#green").is(":visible")) {
        $("button").text("Call Red");
    } else {
        $("button").text("Call Green");
    }
}

ButtonText();
$("button").click(function () {
    $("#green").toggle();
    $("#red").toggle();
    ButtonText();
});

JSFIDDLE DEMO

You didn't include jQuery in your fiddle.

Upvotes: 2

Related Questions