How to add multiple event listeners to one HTML element in JavaScript

1 Answer

0 votes
<!DOCTYPE html>
<html>
    <body>

        <div id="div_id">
            <h2>mouseover click mouseout</h2>
        </div>   

        <p id="p_id"></p>

        <script>
            var elem = document.getElementById("div_id");
            elem.addEventListener("mouseover", mouseoverFunction);
            elem.addEventListener("click", clickFunction);
            elem.addEventListener("mouseout", mouseoutFunction);

            function mouseoverFunction() {
                document.getElementById("p_id").innerHTML += "mouseover<br>";
            }

            function clickFunction() {
                document.getElementById("p_id").innerHTML += "click<br>";
            }

            function mouseoutFunction() {
                document.getElementById("p_id").innerHTML += "mouseout<br>";
            }
        </script>

    </body>
</html>



<!--

run:

mouseover
mouseout
mouseover
mouseout
mouseover
click
click
mouseout
mouseover
click
mouseout
...

-->

 



answered Feb 27, 2020 by avibootz
...