Javascript – catpuring mouse click

While developing my app, I wrote the protype using jQuery, but I only need one method from jQuery, which is click(). I wanted to build it with pure javascript, but have no idea how…(what a newbie!)

So I went to StackOverflow to ask my question, here is the permalink:

Summary of answers:

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 " +;

Breton also posted a fully featured suggestion of the jQuery click() method:

it looks a little bit like you miss more than just the click function of jQuery. You also miss jquery’s selector engine, chaining, and automatic iteration across collections of objects. With a bit more effort you can minimally reproduce some of those things as well.

var myClickCapture = function (selector) {
    var method, name,iterator;
    if(selector.substr(0,1) === "#") {
       method = "getElementById";
       name = selector.substr(1);
       iterator = function(fn) { fn(document[method](name));  };
    } else {
       method = "getElementsByTagName";
       name = selector;
       iterator = function(fn) {
          var i,c = document[method](name);
    }; = function (fn){

    return myClickCapture;


I haven’t tested the code, but in theory, it gets you something like this:

myClickCapture("x").click(function(e){ alert("element clicked") });

Hopefully this gives you a sense of the sorts of things jquery is doing under the covers.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s