10

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; 
adilahmed
  • 1,522
  • 3
  • 17
  • 22
  • This is paragraph Click here..
    test
    – adilahmed Mar 21 '12 at 07:33

3 Answers3

25

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>
lvil
  • 4,326
  • 9
  • 48
  • 76
6

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);
    }
}
Reorx
  • 2,801
  • 2
  • 24
  • 29
  • In IE this function will find the element for binding has no attribute 'addEventListener', then the handler will be assigned to its 'onTYPE' attribute, eg, 'onclick'. – Reorx Mar 21 '12 at 08:28
1

Add a tabIndex attribute to your p element, then you can use the onfocus function.

demo: http://jsfiddle.net/9y7CL/

Waynn Lue
  • 11,344
  • 8
  • 51
  • 76
fengd
  • 7,551
  • 3
  • 41
  • 44