Toggling Elements with JavaScript


/ Published in: JavaScript
Save to your folder(s)

This function allows you to pass two variables that represent ID of two elements on your page. What you click on one of them it hide it and shows another one.


Copy this code and paste it in your HTML
  1. <script type="text/javascript">
  2. function toggle(id, id2){
  3. var toggle_one = document.getElementById(id);
  4. var toggle_two = document.getElementById(id2);
  5. if(toggle_one.style.display == "block"){
  6. toggle_one.style.display = "none";
  7. toggle_two.innerHTML = "Show";
  8. }else{
  9. toggle_one.style.display = "block";
  10. toggle_two.innerHTML = "Hide";
  11. }
  12. }
  13. </script>
  14.  
  15. <a href="#" id="tlink" onclick="toggle('comments', 'tlink');">Show</a> Comments<br><br>
  16. <div id="comments" style="display:none;padding 10px;">Now you can see the comments</div>

URL: http://www.apphp.com/index.php?snippet=javascript-toggle-elements

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.