Will oBOoM Will oBOoM - 2 months ago 13
Javascript Question

Show/hide buttons disappear



$(document).ready(function() {
$("button").click(function() {
$("#incl").toggle(500);
$(this).hide();
$("button").text('hide');
});
});

#incl {
display: none;
}
.incl {
position: absolute;
z-index: 800;
background-color: #00689C;
text-align: left;
padding: 0 5px 5px 5px;
color: #ffffff;
font-size: 1.25em;
border-radius: 3px;
line-height: 1.5em;
margin: -197px -10px 0 0;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function() {
$("#incl").toggle(500);
$(this).hide();
$("button").text('hide');
});
});
</script>

<button>INCLUDES</button>
<div id="incl">
<ul class="incl">
<li>bla bla bla</li>
<li>bla ti bla</li>
<li>bla bla</li>
</ul>
</div>





When I run this scenario the button disappears.
what I would like to happen is the button that echo "includes" must echo "hide" instead
I'm trying to make a button that shows item details and then hide them.

Answer

This should be what you're looking for. Using $(this).text() (without any parameters) will get the current text of the button. I store it, and then swap based on what it's currently set to, and toggle it between "HIDE" or "INCLUDES".

You can also do any of the following:

  • Create two buttons, and two click handlers. 1st show button will show the "hide" button, show the content, and hide the "show" button. The 2nd hide button will do the opposite.
  • Set a boolean if the content is being shown (outside the function). Then, one if/else statement will determine if it's set or not:
if ( contentShown )
{
    $('#content').hide();
    $('#button').text('Show');
}
else
{
    $('#content').show();
    $('#button').text('Hide');
}
contentShown = !contentShown;  //Invert contentShown (Set it to true if false, or false if true)

Please note, I commented out the margin/position in the css to show it in the snippet below.

  $(document).ready(function() {
    $("#toggle").click(function() {
      $("#incl").toggle(500);
      var currentText = $(this).text();
      $(this).text(currentText == "INCLUDES" ? "HIDE" : "INCLUDES");
    });
  });
#incl {
  display: none;
}
.incl {
  /*position: absolute;*/
  z-index: 800;
  background-color: #00689C;
  text-align: left;
  padding: 0 5px 5px 5px;
  color: #ffffff;
  font-size: 1.25em;
  border-radius: 3px;
  line-height: 1.5em;
  /*margin: -197px -10px 0 0;*/
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<button id="toggle">INCLUDES</button>
<div id="incl">
  <ul class="incl">
    <li>bla bla bla</li>
    <li>bla ti bla</li>
    <li>bla bla</li>
  </ul>
</div>

Comments