hiru
hiru

Reputation: 33

Javascript EventListener on button does not work

I tried make button on HTML using Javascript and tried to make button having EventListener

here is code :

function addRefresh(){
 var buildButton = `<button id = "refreshBtn"> testBtn </button>
 <script>
    document.getElementById('refreshBtn').addEventListener("click",function() {alert('hi'););
 </script>
 `
  document.getElementsByClassName('f_l')[0].innerHTML += buildButton;
}

html on website :

<span class="f_l">
    <button id="refreshBtn"> testBtn </button>
    <script>
     document.getElementById('refreshBtn').addEventListener("click",function() {alert('hi'););
    </script>
</span>

but when i click button Event doesn't occur.

I've tried button onclick="myFunction()" also.

Any help would be appreciated. Thanks

Upvotes: 2

Views: 171

Answers (3)

kaushalyap
kaushalyap

Reputation: 13597

Do following and it works fine.

index.html

<body>
    <span class="f_l"></span>
    <script src="main.js"></script>
</body>

main.js

function addRefresh() {

     var buildButton = `<button id="refreshBtn"> testBtn </button>`;
     document.getElementsByClassName("f_l")[0].innerHTML += buildButton;
     document.getElementById('refreshBtn').addEventListener("click",function() {alert("Hi");});
}

addRefresh();

Why?

  • DRY: Do not need to add button via both html and via JS.
  • Add event listener in main.js itself instead of through <script> tag. I think @dev_Fares may be right(

    you can't write the script inside the inner html

).

Upvotes: 1

dev_Fares
dev_Fares

Reputation: 171

I think you can't write the script inside the inner html and you repet it in the html code so there is no need for it inside the js code

function addRefresh()
{ 
var buildButton = '<button id = "refreshBtn"> testBtn </button>';
document.getElementsByClassName('f_l')[0].innerHTML += buildButton;
}

Upvotes: 1

Barr J
Barr J

Reputation: 10919

You miss one carley braces in:

  document.getElementById('refreshBtn').addEventListener("click",function() {alert('hi'););

change it to:

  document.getElementById('refreshBtn').addEventListener("click",function() {alert('hi')});

Upvotes: 2

Related Questions