Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle Visibility in JavaScript

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?

like image 727
Nautilus Avatar asked Dec 23 '22 15:12

Nautilus


1 Answers

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>
like image 98
Ori Drori Avatar answered Dec 28 '22 11:12

Ori Drori