javascriptjqueryclickequivalent

Pure JavaScript equivalent of jQuery click()?


I am building a small app which captures mouse clicks. I wrote the prototype in jQuery but, since it is a small app focusing on speed, embedding jQuery to use just one function would be an overkill.

I tried to adapt this example from JavaScriptKit:

document.getElementById("alphanumeric").onkeypress=function(e){  
    //blah..blah..blah..  
}

but it didn't work when I tried this:

document.getElementsByTagName("x").onclick

What am I doing wrong?


Solution

  • Say you have a list of p tags you would like to capture the click for the <p> tag:

    var p = document.getElementsByTagName("p"); 
    for (var i = 0; i < p.length; i++) { 
        p[i].onclick = function() { 
            alert("p is clicked and the id is " + this.id); 
        } 
    }
    

    Check out an example here for more clarity: http://jsbin.com/onaci/