Reputation: 33
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
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?
<script>
tag. I think @dev_Fares may be right(
you can't write the script inside the inner html
).
Upvotes: 1
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
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