Reputation: 6320
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
Reputation: 3662
Change:
$("#green").show();
$("#red").hide();
To:
$("#green").toggle();
$("#red").toggle();
Upvotes: 0
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();
});
You didn't include jQuery in your fiddle.
Upvotes: 2