20

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 do it inline (I know this is terrible)

<a href="doc.html" onclick="myFunc(); return false">click here</a>

and this causes my javascript to execute for a JS enabled browser, and the link to behave normally for those without javascript?

Now, how do I do the same thing in a non-inline manner?

Stomped
  • 2,010
  • 6
  • 21
  • 25
  • 3
    The way you're doing it there is not terrible. It certainly has disadvantages but it also has advantages over all the other methods (not requiring the document to load before it will work being the main one). Don't let yourself be brainwashed by the propaganda of unobtrusiveness. – Tim Down Jun 03 '10 at 13:17

6 Answers6

30

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.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • What is the difference between using `onClick` property and `addEventListener` function? Which is better? I believe there is also a `click` function, so could you also do `myAnchor.click = (event) => ...`? – Luke T O'Brien Jun 22 '17 at 10:27
  • 1
    @LukeTO'Brien in short: onClick property can be overwritten while addEventListener can be used multiple times for binding to the same event on the same element. See this nice answer here: https://stackoverflow.com/questions/6348494/addeventlistener-vs-onclick – ThdK Aug 27 '18 at 08:37
10

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:

function myFunc(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) {
  // ...
});
KreepN
  • 8,528
  • 1
  • 40
  • 58
Jordan Running
  • 102,619
  • 17
  • 182
  • 182
  • 1
    Remember that IE does not support `addEventListener` - you have to use `attachEvent` instead. – el.pescado - нет войне Jun 03 '10 at 15:18
  • 1
    IE has addEventListener since IE9. You have to decide for yourself if you want to build web apps for users using < IE9. All other major browser-device combo do support addEventListener. Source: https://caniuse.com/#search=addEventListener – ThdK Aug 27 '18 at 08:34
  • there is a typo kindly fix the method name, it is getElementById and not getElementyById. – MasoodRehman Sep 27 '18 at 17:53
6

This is a nice cross-browser method

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


on(document.getElementById("myAnchor"), "click", function(){
    alert(this.href);
});
Sean Kinsey
  • 37,689
  • 7
  • 52
  • 71
4

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

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
4

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

document.getElementById("the id").onclick = function{ ... }
Lloyd
  • 29,197
  • 4
  • 84
  • 98
0

You don't have to use jQuery, but you could try John Resig's popular addEvent funciton.

addevent(elem, "click",clickevent);  

function addEvent ( obj, type, fn ) {
      if ( obj.attachEvent ) {
        obj["e"+type+fn] = fn;
        obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
        obj.attachEvent( "on"+type, obj[type+fn] );
      } else
        obj.addEventListener( type, fn, false );
    }

There are more to be considered to'properly' bind an event on HTML tags in pure javascript.

http://www.pagecolumn.com/javascript/bind_event_in_js_object.htm

unigg
  • 466
  • 3
  • 8
  • 1
    This is not a good method as it depends on the Functions toString actually returning the functions body for the event handling. This is not guaranteed. – Sean Kinsey Jun 03 '10 at 15:00