Search code examples
javascriptjquerytoggletogglebutton

How to change toggle button text when pressed?


I would like to be able to press a button that says "hide" and then say "show" when the user clicks the button. In the code below the toggle part works, but now I need the "hide" text to turn to "show" once the content is hidden.

I took the toggle code from: http://thedesignspace.net/MT2archives/000298.html#.UW61YqKG33U

 <script type="text/javascript">
    function toggle(element) {
    document.getElementById(element).style.display = (document.getElementById(element).style.display == "none") ? "" : "none";
    }
    </script>

    <div class="ISBody">
     <h5>Header</h5>
     <div class="ISTopLink"><a href="#ISTop">Return to Top</div>
     <div class="ISHide"><a href="javascript:toggle('pos')">Hide Products - </a></div>
     <hr>
     <div id="pos" style="display: block;">
      <div class="ISProductBody">
       <div class="ISSubHead"><A HREF="#">Prodcut Name</A></div>
      <div class="ISList">
       <ul>
        <li>Text here</li>
        <li>Text here</li>
        <li>Text here</li>
        <li>Text here</li>
      </ul>
      </div>
    </div>
    </div>

Solution

  • Change your button code to something like this:

    <div class="ISHide" onclick="toggle(this)"><a href="#" >Hide Products</a></div>
    

    And change your script to something like this

    <script type="text/javascript">
    function toggle (t) {
    if (t.childNodes[0].innerHTML == "Hide Products") {
        t.childNodes[0].innerHTML = "Show Products";
    } else {
        t.childNodes[0].innerHTML = "Hide Products";
    }
    }
    </script>