Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind event to element using pure Javascript

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.

like image 717
Wancieho Avatar asked Jul 23 '13 20:07

Wancieho


People also ask

How we can bind an event for a element in JavaScript?

jQuery bind() Method Use the on() method instead. The bind() method attaches one or more event handlers for selected elements, and specifies a function to run when the event occurs.

What is bind event in JavaScript?

Purpose. The event binding allows you to add an event handler for a specified event so that your chosen JavaScript function will be invoked when that event is triggered for the associated DOM element. This can be used to bind to any event, such as keypress , mouseover or mouseout .

How do you bind an event?

To bind to an event you use the Angular event binding syntax. This syntax consists of a target event name within parentheses to the left of an equal sign, and a quoted template statement to the right. Create the following example; the target event name is click and the template statement is onSave() .


1 Answers

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

like image 134
Dan Tao Avatar answered Sep 18 '22 15:09

Dan Tao