If your not familiar with natural javascript and your only used to using a library like jQuery, then you might be surprised to learn that javascript doesn’t have a predefined toggle function that you can just call up when you want. You need to create your own before you can use it. Here is a bare bones demonstration of toggling in plain old ordinary javascript.
This is about as simple as it can get. I’ll add comments soon. Click the button to toggle the paragraph beneath. You can copy the basic html source in case you want to play around with it
I am a paragraph of text. You can display me or hide me by clicking on the button. Don’t believe me? Go ahead and try it then. Go on, I dare you to. I’ve got to say something to make this look like a sizable enough paragraph for you to show or hide at your whimsy! Are we even up to four lines yet? I say a decent paragraph should probably contain at least four lines as a bare minimum, don’t you think?
<!DOCTYPE html> <html> <body> <h1>Toggler</h1> <button id="toggler" type="button" onclick="toggle('para')">Hide paragraph</button> <p id="para">I am a paragraph of text. You can display me or hide me by clicking on the button.</p1> <script> function toggle( targetId ){ var button = document.getElementById("toggler"); var target = document.getElementById( targetId ); if (target.style.display == "none") { target.style.display = ""; button.innerHTML = "Hide paragraph"; } else { target.style.display = "none"; button.innerHTML = "Show paragraph"; } } </script> </body> </html>
Here’s the javascript all by its lonesome so I can add plenty of comments.
function toggle( targetId ){ var button = document.getElementById("toggler"); var target = document.getElementById( targetId ); if (target.style.display == "none") { target.style.display = ""; button.innerHTML = "Hide paragraph"; } else { target.style.display = "none"; button.innerHTML = "Show paragraph"; } } // comments coming soon!