0

I am trying to make multiple elements appear with the click of a button using one script.

This is supposed to happen: button b1 hides p1 and button b2 hides p2.

This is my current code:

<html>
<body>

<p id="p1">Disapear 1</p>

<button id="b1" onclick="toggle(p1)">hide 1</button>

<p id="p2">Disapear 2</p>

<button id="b2" onclick="toggle(p2)">hide 2</button>

<script>
function toggle(id) {
  var x = document.getElementById("id");
  if (x.style.visibility === "hidden") {
    x.style.visibility = "visible";
  } else {
    x.style.visibility = "hidden";
  }
}
</script>

</body>
</html>

Is there any way to carry information with the click of a button to the function.

2 Answers2

0

A clean, DRY solution would be to avoid inline handlers and iterate over all buttons on the page. Add a click listener to each that navigates to the button's previousElementSibling to toggle a class that either hides or shows the <p>:

for (const button of document.querySelectorAll('button')) {
  button.addEventListener('click', ({ target }) => {
    target.previousElementSibling.classList.toggle('hidden');
  });
}
.hidden {
  visibility: hidden;
}
<p>Disapear 1</p>
<button>hide 1</button>

<p>Disapear 2</p>
<button>hide 2</button>

You can also use event delegation to attach just one listener to the parent, instead of a listener to each button:

window.addEventListener('click', ({ target }) => {
  if (target.matches('button')) {
    target.previousElementSibling.classList.toggle('hidden');
  }
});
.hidden {
  visibility: hidden;
}
<p>Disapear 1</p>
<button>hide 1</button>

<p>Disapear 2</p>
<button>hide 2</button>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
-1

Try this function and call each button with its ID.

function contactToggle(ElementID) {
  x = document.getElementById(ElementID);
  if (x.style.visibility === "visible") {
    x.style.visibility = "hidden";
  } else {
    x.style.visibility = "visible";
  }
}

For example you have buttons like:

<button id="hey">Click me</button>
<button id="hello">Click me</button>

In your javascript:

contactToggle(document.getElementById('hey'));
contactToggle(document.getElementById('hello'));
Bruce Salcedo
  • 167
  • 1
  • 7
  • How do I reopen this question, I made it much more clear. Also it is my first time using this site. – Tyler Bowers Aug 27 '20 at 17:39
  • @TylerBowers - Members of the community with sufficient reputation can vote on whether to re-open a question (e.g. after the OP has edited it, like you have). Read more about that process [here](https://stackoverflow.com/help/reopen-questions). You currently have 2 of the 3 needed "reopen" votes. – andrewJames Aug 27 '20 at 18:39