Add event handler to HTML element using javascript

You can add event listener.
Smth. like this:

 var el = document.getElementById("p1");
if (el.addEventListener) {
        el.addEventListener("click", yourFunction, false);
    } else {
        el.attachEvent('onclick', yourFunction);
    }  

(thanks @Reorx)

Explanation Here

Complete code (tested in Chrome&IE7):

<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=windows-1255">
        <script type="text/javascript">
            window.onload =function (){
            var el = document.getElementById("p1");
            if (el.addEventListener) {
                el.addEventListener("click", yourFunction, false);
            } else {
                el.attachEvent('onclick', yourFunction);
            }
            };
            function yourFunction(){
                alert("test");
            }
        </script>
    </head>
    <body>
        <p id="p1">test</p>

    </body>
</html>

Leave a Comment