31

I'm writing an API and unfortunately need to avoid any jQuery or 3rd party libraries. How exactly are the events bound to elements through jQuery?

jQuery example:

$('#anchor').click(function(){
    console.log('anchor');
});

I'm close to writing a onClick attribute on the element out of frustration, but I would like to understand the link between the jQuery event and DOM element.

How exactly does the element know to fire a jQuery event when the markup itself is not changed? How are they catching the DOM event and overriding it?

I have created my own Observer handler but cant quite understand how to link the element to the Observer events.

4444
  • 3,541
  • 10
  • 32
  • 43
Wancieho
  • 708
  • 1
  • 7
  • 25

2 Answers2

68

Here's a quick answer:

document.getElementById('anchor').addEventListener('click', function() {
  console.log('anchor');
});

Every modern browser supports an entire API for interacting with the DOM through JavaScript without having to modify your HTML. See here for a pretty good bird's eye view: http://overapi.com/javascript

Adam Huffman
  • 1,031
  • 14
  • 21
Dan Tao
  • 125,917
  • 54
  • 300
  • 447
  • 3
    You can read more about `addEventListener` here https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener Do scroll down to "Legacy Internet Explorer and attachEvent" know about IE<9 support. – vsr Jul 23 '13 at 20:53
  • what about hidden elements? – user924 Sep 02 '17 at 12:34
10

You identify the element by id, in this case anchor, by:

var el = document.getElementById('anchor');

Then you need to assign your click event:

el[window.addEventListener ? 'addEventListener' : 'attachEvent']( window.addEventListener ? 'click' : 'onclick', myClickFunc, false);

And finally, the event's function would be something like:

function myClickFunc()
{
    console.log('anchor');
}

You could simplify it or turn it into a one-liner if you do not need compatibility with older browsers and and a range of browsers, but jQuery does cross-browser compatibility and does its best to give you the functionality you are looking for in as many older browsers as it can.