0

I have 6 elements hidden by default that is displayed when clicking on text. However, I can get the function working with a button and onclick but not on text.

My code:

<button type="button" onclick="showAcc('acc-mobil')">Mobil</button>
<p id="showmob">Mobil</p>

<script>
document.getElementById("showmob").addEventListener("click", showAcc('acc-mobil');

function showAcc(param) {
document.getElementById("acc-mobil").style.display = "none" ;
document.getElementById("acc-faktura").style.display = "none" ;
document.getElementById("acc-vaxel").style.display = "none" ;
document.getElementById("acc-internet").style.display = "none" ;
document.getElementById("acc-kontor").style.display = "none" ;
document.getElementById("acc-ab").style.display = "none" ;
document.getElementById(param).style.display = "block" ;
}
</script>

In the example above clicking the button works but not the div. What am I doing wrong?

  • 5
    `.addEventListener("click", showAcc('acc-mobil');` is missing a closing bracket, and is also calling that function immediately. See this question: [How to pass arguments to addEventListener listener function?](https://stackoverflow.com/questions/256754/how-to-pass-arguments-to-addeventlistener-listener-function) – DBS Nov 07 '22 at 09:42
  • use `function() { showAcc('acc-mobil'); }` instead, to avoid the immediate call. – Hasan Riza Nov 07 '22 at 09:45

0 Answers0