HOBALL 筆記簿

July 23, 2009

Javascript – catpuring mouse click

Filed under: Javascript — Tags: , , — hoball @ 1:00 pm

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: www.stackoverflow.com

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 " + this.id);
    }
}

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);
          for(i=0;i<c.length;i++){
             fn(c[i]);
       };
    };
    myClickCapture.click = function (fn){
         iterator(function(e){
            e.onclick=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 Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: