7

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?

Pang
  • 9,073
  • 146
  • 84
  • 117
Nautilus
  • 91
  • 1
  • 1
  • 5

3 Answers3

8

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>
Ori Drori
  • 166,183
  • 27
  • 198
  • 186
3

you could test the CSS property and set a var once the first check is made.

var $test;
function show() {
  if ((document.getElementById("p").style.visibility = "hidden") | ($test!="visible"))
  {document.getElementById("p").style.visibility = "visible";
  $test="visible"
  }
  else  
  {document.getElementById("p").style.visibility = "hidden";
  $test="hidden"}
}
#p {
  visibility: hidden;
}
    <button onclick="show() ">Click me</button>

    <p id="p">hi</p>
G-Cyrillus
  • 94,270
  • 13
  • 95
  • 118
3

Here's the non-JS approach, using a hidden checkbox to store the state:

input:checked + #text { display: none; }
<label for="check">Press me</label>

<input id="check" type="checkbox" style="display: none; ">

<p id="text">This is some text.</p>