hidden text is not visible on button first click

Oliv

I have a webpage with a button and a paragraph of text. A click on the button should show or hide the paragraph. When the paragraph is shown initially, everything works fine. But when the paragraph is hidden, the first click has no consequence - the code works fine from the second click on. Why? How can I fix it?

Here is my code:

function show_hide(id) {
  var e = document.getElementById(id);
  if (e.style.display == 'block' || e.style.display == '') {
    e.style.display = 'none';
  } else {
    e.style.display = 'block';
  }
}
.hidden {
  display: none;
}
<input type="button" onclick="show_hide('text_to_show_hide')" value="Show/Hide">
<p id="text_to_show_hide" class="hidden">This is the text that I want to show/hide.</p>

Sampson Crowley

You need consistency. you are starting off the paragragh with the class hidden, which keeps the paragraph hidden, but does not have the 'display' property on the inline style.

either add and remove the hidden class:

function show_hide(id) {
  var e = document.getElementById(id);
  e.classList.toggle('hidden');
}
.hidden{
  display:none;
}
<input type="button" onclick="show_hide('text_to_show_hide')" value="Show/Hide">
 
<p id="text_to_show_hide" class="hidden">This is the text that I want to show/hide.</p>

OR use only inline styles

function show_hide(id) {
  var e = document.getElementById(id);
  if (e.style.display == 'block' || e.style.display==''){
    e.style.display = 'none';
  } else {
    e.style.display = 'block';
  }
}
<input type="button" onclick="show_hide('text_to_show_hide')" value="Show/Hide">
 
<p id="text_to_show_hide" style='display:none'>This is the text that I want to show/hide.</p>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related