JLeno46
JLeno46

Reputation: 1269

simple function fires when using onclick, doesn't fire when using addEventListener in JS

the function doesn't work when called with addEventListener in JS, I used the same method for other function in the same project and they all work fine.

I've made it a higher order function and still doesn't fire, I wrap its expression in another function, still doesn't work.


    function contenutoSkills(nomelinguaggio, item1, item2, item3) {
  document.getElementById("linguaggio").innerHTML=nomelinguaggio;
  document.getElementById("programma1").innerHTML=item1;
  document.getElementById("programma2").innerHTML=item2;
  document.getElementById("programma3").innerHTML=item3;
}
const button = document.getElementById('button');

button.addEventListener('click', () => contenutoSkills('HTML', 'PG1', 'PG2', 'PG3'));

<button id='button'>click me<button>

<p id="linguaggio"></p>
  <ul>
     <li><p id="programma1">Programma1</p></li>
     <li><p id="programma2">Programma2</p></li>
     <li><p id="programma3">Programma3</p></li>
  </ul>

text one and text two should appear in p when the button is clicked, but nothing happens. If I add onclick="writeText("text one", "text two") in HTML it works fine but I don't want to do things this way. thanks for answers.

Upvotes: 0

Views: 44

Answers (1)

RishiC
RishiC

Reputation: 826

You could use onclick property of the button instead of addEventListener.

HTML:

<button id='button' onclick="contenutoSkills('html','pg1','pg2','pg3')">click me<button>

<p id="linguaggio"></p>
  <ul>
     <li><p id="programma1">Programma1</p></li>
     <li><p id="programma2">Programma2</p></li>
     <li><p id="programma3">Programma3</p></li>
  </ul

And within the <script> tag, this would the JavaScript code:

    function contenutoSkills(nomelinguaggio, item1, item2, item3) {
  document.getElementById("linguaggio").innerHTML=nomelinguaggio;
  document.getElementById("programma1").innerHTML=item1;
  document.getElementById("programma2").innerHTML=item2;
  document.getElementById("programma3").innerHTML=item3;
}

Upvotes: 2

Related Questions