Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add event handler to HTML element using javascript

Tags:

javascript

I want to add an event handler to a paragraph for when any user clicks on it. For example, I have a paragraph which would show an alert when a user clicks it, but without using "onclick" on HTML.

 <p id="p1">This is paragraph Click here..</p>
 <a href="http://www.google.com" id="link1" >test</a>
 document.getElementById('p1').onmouseover  = paragraphHTML; 
like image 387
adilahmed Avatar asked Mar 21 '12 07:03

adilahmed


2 Answers

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>
like image 91
lvil Avatar answered Nov 20 '22 00:11

lvil


To suit most situations, you can write a function to handle this:

var bindEvent = function(element, type, handler) {
    if (element.addEventListener) {
        element.addEventListener(type, handler, false);
    } else {
        element.attachEvent('on'+type, handler);
    }
}
like image 6
Reorx Avatar answered Nov 19 '22 23:11

Reorx