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?
The equivalent to $() or jQuery() in JavaScript is querySelector() or querySelectorAll() , which, just like with jQuery, you can call with a CSS selector.
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.
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.
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.
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/
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With