Skip to content Skip to sidebar Skip to footer

How Do I Bind A Click To An Anchor Without A Framework (javascript)

I know this is easily done in jQuery or any other framework, but that's not really the point. How do I go about 'properly' binding a click event in pure javascript? I know how to d

Solution 1:

If you need to assign only one click event, you can assign onclick:

If you have an ID:

myAnchor = document.getElementById("Anchor");myAnchor.onclick = function() { myFunc(); return false; }

you can also walk through all anchors:

anchors = document.getElementsByTagName("a");

for (var i = 0; i < anchors.length; i++) {   

 anchors[i].onclick = .....

}

There's also a document.getElementsByClassName to simulate jQuery's class selector but it is not supported by all browsers.

If it could be that you need to assign multiple events on one element, go with addEventListener shown by @Jordan and @David Dorward.

Solution 2:

The basic way is to use document.getElementById() to find the element and then use addEventListener to listen for the event.

In your HTML:

<a href="doc.html"id="some-id">click here</a>

In your JavaScript:

functionmyFunc(eventObj) {
  // ...
}

var myElement = document.getElementById('some-id');
myElement.addEventListener('click', myFunc);

Or you can use an anonymous function:

document.getElementById('some-id').addEventListener('click', function(eventObj) {
  // ...
});

Solution 3:

This is a nice cross-browser method

var on = (function(){
    if ("addEventListener"inwindow) {
        returnfunction(target, type, listener){
            target.addEventListener(type, listener, false);
        };
    }
    else {
        returnfunction(object, sEvent, fpNotify){
            object.attachEvent("on" + sEvent, function(){
                fpNotify(window.event);
            });
        };
    }
}());


on(document.getElementById("myAnchor"), "click", function(){
    alert(this.href);
});

Solution 4:

The standard go to for this question is on Quirks Mode: http://www.quirksmode.org/js/events_advanced.html

Solution 5:

Give it an ID and you should be able to do:

document.getElementById("the id").onclick = function{ ... }

Post a Comment for "How Do I Bind A Click To An Anchor Without A Framework (javascript)"