document.querySelector('#showButton').addEventListener('click', showBtn);
function showBtn(){
let containerDivElement = document.querySelector('#button-container');
let button = document.createElement('button');
button.id = "btnId";
button.innerHTML = "Click me!";
// append elemnt to the container div
containerDivElement.appendChild(button);
document.querySelector('#btnId').addEventListener('click', createAlert('Ouch!'));
}
function createAlert(message){
alert(message);
}
.container{
width: 75%;
margin: 0 auto;
display: flex;
flex-wrap: wrap;
justify-content: space-around;
}
<div class="container">
<button id="showButton">Show button</button>
<div class="card-form-container" id="button-container">
</div>
</div>
I'm a junior developer who's developing a deep understanding of JavaScript, and while I was working on some demo a weird event grasped my attention.
The previous demo showcases the weird event, I used an addEventListener() to attach an event handler to the showButton element of type click which causes the showBtn() to be called that creates other button element and appends it to the container div.
Also, In the showBtn() I created other addEventListener() to attach an event handler to the second button of type click that causes createAlert() to be called and this function takes an argument (message) to show it in an alert.
The weird event is when I pass a parameter to the createAlert function using addEventListener() of the element that has been created by the showBtn(), the createAlert() click event occurs when the ShowButton is clicked.
As I found out, it's wrong to pass a parameter in this way, but this made me curious to know the reason for this wired result.