views:

324

answers:

4

Hello,
I am building a small apps which has to capture mouse click. I wrote the prototype in jquery.
Since it is a small apps focusing on speed, embedding jquery.js to use just one function would be an overkill.

I am not very experienced in pure javascript, would you show me some hints on writing pure javascript code to serve this function?

I see this example on JavascriptKit:

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

but it doesn't seem to work for

document.getElementsByTagName("x").onclick

Thank you!

A: 
document.getElementsByTagName("x")

returns an array of elements having the tagname 'x'.

You have to right event for each element in the returned array.

rahul
+3  A: 

In your example you are using getElementsByTagName, which returns you an array of DOM elements, you could iterate that array and assign the onclick handler to each element, for example:

var clickHandler = function(){
  alert('clicked!');
}

var elements = document.getElementsByTagName('div'); // All divs

for(var i = 0; i<elements.length; i++){
  elements[i].onclick = clickHandler;
}
CMS
Thanks for your help. This works.
hoball
A: 

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/

Dhana
Thanks for your help. This works.
hoball
A: 

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.

Breton
Thanks for this suggestion. I will save this down for my future developments.
hoball