Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of jQuery code in Javascript

This is the jQuery code I have

$('p').click(function(){
    alert("click successful!");
});

This is the JS code I could come up with

window.onload = function() {
    var para = document.getElementsByTagName('p');
    for(var i = 0; i < para.length; i++) {
        para[i].addEventListener('click',function(){
            alert("click successful!");
        });
    }
}

The Javascript code is too bulky, is there a way where I can select a tag by its name and write the code as -

"If any 'p' tag is clicked, alert('click successful')"

instead of looping through all the <p></p> tags? Any alternative way using tag name?

like image 268
Siddharth Thevaril Avatar asked Dec 09 '22 01:12

Siddharth Thevaril


2 Answers

You can use event delegation - add a click handler to a higher level element and check event.target

document.body.addEventListener("click", function(e) {
    if (e.target.tagName.toLowerCase() == "p") alert("click succeeded");
});

Demo: http://jsfiddle.net/jdkr3sch/

like image 107
Dennis Avatar answered Dec 11 '22 11:12

Dennis


jQuery is "less code" because you're calling a pre-written function. Don't want to use jQuery? Then write your own functions.

function addEventToElements(tagname,handler) {
    var elems = document.getElementsByTagName(tagname);
    for(var i = 0, l = elems.length; i<l; i++) {
        elems[i].addEventListener('click',handler);
    }
}

Now in your actual code, you can just write:

addEventToElements('p',function() {alert("click succeeded");});

Congratulations, you have re-invented jQuery.

... Or not, because the reason jQuery is so popular is that it does a lot more. Things like normalising browser support (for those that use attachEvent or the old onEventName handlers) are half the reason jQuery exists, and you'd have to account for all of them in your own re-invention ;)

like image 30
Niet the Dark Absol Avatar answered Dec 11 '22 10:12

Niet the Dark Absol