pku pku - 1 year ago 48
HTML Question

Display paragraph with different ids on a button click in HTML

I have a single button on my HTML page and two paragraphs say id = 'para_1' and id = 'para_2'. I want to display content in para_1 on load the page and on every second click of the button and content in para_2 on every first click of the button.

I have the following code so far:

<html>
<head>
</head>
<body>

<script language="JavaScript">
function setVisibility(id) {
if(document.getElementById('bt1').value=='Hide Layer'){
document.getElementById('bt1').value = 'Show Layer';
document.getElementById(id).style.display = 'none';
}else{
document.getElementById('bt1').value = 'Hide Layer';
document.getElementById(id).style.display = 'inline';
}
}

</script>
<input type=button name=type id='bt1' value='Show Layer' onclick="setVisibility('para_2');";>

<p id ="para_1"> display this is on load and second click</p>
<p id ="para_2"> display this on first click </p>
<br><br>
</body>
</html>


what it is currently doing is loading both the paras on load and on the second click hiding para with id = 'para_2'.

I am very new to HTML and am really stuck on this part.
Any help will be appreciated.
Thank you.

Answer Source

You could set the visibility of the second paragraph to display:none inline so the paragraph is hidden on page load and toggle the visibility of the two paragraphs using the ternary operator, removing the need for the id parameter:

<p id="para_2" style="display:none">display this on first click</p>

window.setVisibility = function() {
  var para1 = document.getElementById("para_1");
  var para2 = document.getElementById("para_2");

  para1.style.display = para1.style.display === 'none' ? '' : 'none';
  para2.style.display = para1.style.display === 'none' ? '' : 'none';
}
<input type=button name=type id='bt1' value='Show Layer' onclick="setVisibility();">
<p id="para_1">display this is on load and second click</p>
<p id="para_2" style="display:none">display this on first click</p>

If you used jQuery you could achieve the same functionality by toggling the visibility of paragraphs when clicking the button:

window.setVisibility = function() {
  var $para = $("p");
  $para.toggle();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=button name=type id='bt1' value='Show Layer' onclick="setVisibility();">
<p id="para_1">display this is on load and second click</p>
<p id="para_2" style="display:none">display this on first click</p>