0

So, I was experiment with functions and events when I bumped into different behaviors from something I was expecting to behave in the same way.

My goal was to make a button that, when clicked, it would create a new paragraph with some content on it at the end of my container (below the button).

When using the onclick=function() attribute, my new paragraph would be created multiple times as I clicked the button.

However, when using the .onclick event on my JS file, it would only run once, not being able to create multiple paragraphs when clicking the button.

I've also tried to use .addEventListener() instead of JS onclick, but it runs the same way.

Any idea why does this happen?

1. WITH ONCLICK HTML ATTRIBUTE

<body>
    <div class="container">
        <button type="button" id="buy-btn" onclick="thanks()">Buy!</button>
    </div>
    <script src="testing.js"></script>
</body>
let containerEl = document.querySelector(".container");

const thanks = () => {
    containerEl.innerHTML += "<p>Thanks for buying!</p>";
};

2. WITH ONCLICK JS EVENT

<body>
    <div class="container">
        <button type="button" id="buy-btn">Buy!</button>
    </div>
    <script src="testing.js"></script>
</body>
let containerEl = document.querySelector(".container");

const thanks = () => {
    containerEl.innerHTML += "<p>Thanks for buying!</p>";
};

let buyBtn = document.querySelector("#buy-btn");
buyBtn.onclick = thanks;

3. WITH ADDEVENTLISTENER JS METHOD

let containerEl = document.querySelector(".container");

const thanks = () => {
    containerEl.innerHTML += "<p>Thanks for buying!</p>";
};

let buyBtn = document.querySelector("#buy-btn");
buyBtn.addEventListener("click", thanks);

Here are the codepen for each example:

  1. onclick HTML attribute
  2. onclick JS event
  3. addEventListener JS method

0 Answers0