Events - SelfishHellfish/JS_Ref GitHub Wiki
event handlers
a button can be identified and set to print 'clicked' on click
var btn = document.querySelector('button');
btn.onclick = function() {console.log'clicked!')}
can console.log(btn)
to see all event handlers available for that html element, or google for list. event handlers begin with the prefix 'on'. if multiple e.g. onclick
event handlers are set up this way, only the last will be executed
event listeners
can above problem by assigning event listeners to elements:
btn.addEventListener('click', listener1);
an additional parameter of 'True' will ensure that any function listening to events on the parent div is executed first
function listener1(event) {console.log('click!')}
...adding as many listeners to handle events as you'd like
can also set timeouts for listeners, e.g.
setTimeout(function() {btn.removeEventListener('click', listener1);}, 2000;)
event behavior
the event object is passed to listener functions by default, and the behavior of events may be modified by passing methods to this object. e.g. given a div within a div and functions listening to clicks on each, clicking on the inner div will propogate up and result in execution of both functions. to stop this, add the following to the listener function of the inner div:
event.stopPropagation();
useful properties that can be used on the event object are:
event.target.style.backgroundColor = 'red';
, to access the html element which triggered the event/function and change its color
console.log(event.clientX, event.clientY)
to get the x, y coordinates of the click event
google or log to the console the event object to see its available properties/methods
cheat sheet