Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

document.getElementsByTagName("x").onclick

What am I doing wrong?

like image 471
hoball Avatar asked Jul 22 '09 04:07

hoball


People also ask

What can replace jQuery () in a function call?

The equivalent to $() or jQuery() in JavaScript is querySelector() or querySelectorAll() , which, just like with jQuery, you can call with a CSS selector.

What is click in jQuery?

jQuery click() MethodThe click event occurs when an element is clicked. The click() method triggers the click event, or attaches a function to run when a click event occurs.

What is the difference between on click and click in jQuery?

So onclick creates an attribute within the binded HTML tag, using a string which is linked to a function. Whereas . click binds the function itself to the property element.

Is jQuery native JavaScript?

Vanilla JS helped the developers in creating dynamic websites. Then came jQuery, a library of tools created by developers around the world, using Javascript. In simple words, jQuery is a lightweight and easy to use JavaScript library that helps in creating complex functionalities with few lines of coding.


2 Answers

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/

like image 52
DLS Avatar answered Sep 26 '22 03:09

DLS


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;
}
like image 43
Christian C. Salvadó Avatar answered Sep 23 '22 03:09

Christian C. Salvadó