peterHasemann peterHasemann - 2 years ago 62
HTML Question

switching button texts by using toggle states

When clicking on a button, this button should change its text. The button itself toggles another element.



function switchBtnText(btn, contentElement, contentText) {
var stateText = contentElement.is(":hidden") ? "hide" : "show";
contentText += " <b>" + stateText + "</b>";
$(btn).html(contentText);
}

function toggleOne() {
$("#p1").slideToggle();
switchBtnText($("#btn1"), $("#p1"), "Text 1");
}

function toggleTwo() {
$("#p2").slideToggle();
switchBtnText($("#btn2"), $("#p2"), "Text 2");
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn1" onclick="toggleOne()">Text 1 <b>hide</b></button>
<button id="btn2" onclick="toggleTwo()">Text 2 <b>hide</b></button>

<p id="p1">Text _ 1 _</p>
<p id="p2">Text _ 2 _</p>





So the first click on the button is fine. The button switches its text to "show". But when clicking agai (the element is shown) it does not switch back to the "hide" text.

I use
contentElement.is(":hidden")
to check if the element is hidden or shwon.

Answer Source

You have to call .is(":hidden") before you use .slideToggle()

function toggleOne() {
  var isVisible = $("#p1").is(":hidden");
  $("#p1").slideToggle();
  switchBtnText($("#btn1"), isVisible, "Text 1");
}

function switchBtnText(btn, isVisible, contentText) {
  var stateText = isVisible ? "hide" : "show";
  contentText += " <b>" + stateText + "</b>";
  $(btn).html(contentText);
}

function toggleOne() {
  var isVisible = $("#p1").is(":hidden");
  $("#p1").slideToggle();
  switchBtnText($("#btn1"), isVisible, "Text 1");
}

function toggleTwo() {
  var isVisible = $("#p2").is(":hidden");
  $("#p2").slideToggle();
  switchBtnText($("#btn2"), isVisible, "Text 2");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn1" onclick="toggleOne()">Text 1 <b>hide</b></button>
<button id="btn2" onclick="toggleTwo()">Text 2 <b>hide</b></button>

<p id="p1">Text _ 1 _</p>
<p id="p2">Text _ 2 _</p>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download