I'm trying to make a button that shows a paragraph on click and hides it on a second click. Instead of using a more traditional method, I went with using JavaScript to change the style from visibility:hidden
to visibilitiy:visible
.
<style>
#p {
visibility:hidden;
}
</style>
<button onclick="show() ">Click me</button>
<p id="p">hi</p>
<script>
function show() {
document.getElementById("p").style.visibility = "visible";
}
</script>
How can I do this without jQuery?
You can use Element#classList to toggle a class on and off:
var p = document.getElementById("p"); // get a reference to p and cache it
function show() {
p.classList.toggle('hideP'); // toggle the hideP class
}
document.getElementById('button').addEventListener('click', show); // add an event listener to the button
.hideP {
visibility: hidden;
}
<button id="button">Click me</button>
<p id="p" class="hideP">hi</p>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With