Skip to content
Advertisement

using addEventListener or onclick method for executing a function when someone clicks on it?

I am practicing DOM events and notice that I can use addEventListener or onclick method both for triggering a function when we click on the button but I want to know is there any logical difference between them? What should we use when? I am fairly new to programming.

Here is my code,

<!DOCTYPE html>
<html>
    <body>
        <h2>Testing</h2>

        <button id="myBtn-1">BUTTON-1</button>
        <button id="myBtn-2">BUTTON-2</button>

        <p id="demo"></p>

        <script>
            //Event for button 1
            document
                .getElementById('myBtn-1')
                .addEventListener('click', displayDate);

            //Event for button 2
            document.getElementById('myBtn-2').onclick = displayDate;

            //function to get the current date and time
            function displayDate() {
                document.getElementById('demo').innerHTML = Date();
            }
        </script>
    </body>
</html>

Advertisement

Answer

The main difference is that onclick is just a property. Like all object properties, you may have one inline event assigned. If you write more than once, it will be overwritten. addEventListener() on the other hand, can have multiple event handlers applied to the same element. It doesn’t overwrite other present event handlers.

heres a good link https://medium.com/@tshlosberg/addeventlistener-vs-onclick-which-one-should-you-use-47550d7e7487

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement