JavaScript - Event Handling

javascript-dom

Important:
http://help.dottoro.com/larrqqck.php - a list of events
https://www.perimeterx.com/tech-blog/2019/list-every-event-that-exists-in-the-browser/
http://www.asquare.net/javascript/tests/KeyCode.html
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent
https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
http://quirksmode.org/dom/events/ - Event compatibility tables
https://stackoverflow.com/questions/2490825/how-to-trigger-event-in-javascript
http://blog.nathansplace.co.uk/2015/programmatically-firing-events-in-javascript
http://davidwalsh.name/dom-events-javascript - printed, not yet read
http://unixpapa.com/js/key.html
https://developer.mozilla.org/en-US/docs/Web/Events
https://developer.mozilla.org/en-US/docs/Web/API/Event
https://developer.mozilla.org/en-US/docs/Web/Guide/Events
http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-eventgroupings-mutationevents
http://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113/events.html#Events-MutationEvent - printed, not yet read
http://addyosmani.com/blog/mutation-observers/ - printed, not yet read

http://quirksmode.org/js/events_tradmod.html
http://quirksmode.org/js/events_advanced.html

http://www.quirksmode.org/js/events_order.html
http://www.howtocreate.co.uk/tutorials/javascript/domevents
http://blog.reybango.com/2010/04/14/my-solution-to-google-chrome-safari-double-firing-the-mouseup-event-when-selecting-text/
http://davidwalsh.name/pointer-events
http://stackoverflow.com/questions/1029241/javascript-object-watch-for-all-browsers#answer-1270182
http://davidwalsh.name/customevent
http://davidwalsh.name/browser-repaint
JavaScript from Null: Cross-Browser Event Binding
Custom events in JavaScript
Using standard DOM event methods for Internet Explorer
http://www.webdevelopersjournal.com/articles/jsevents2/jsevents2.html
http://coding.smashingmagazine.com/2012/08/17/javascript-events-responding-user/
http://www.sitepoint.com/emerging-patterns-javascript-event-handling
http://davidwalsh.name/dom-events-javascript

http://www.quirksmode.org/js/introevents.html
http://en.wikipedia.org/wiki/DOM_Events
http://video.yahoo.com/watch/4943143/13163203
http://yuiblog.com/blog/2009/04/27/video-ppk-jsevents/

// JavaScript - Event handling:

if(window.attachEvent) {
  window.attachEvent('onresize', function(event) {
    alert('attachEvent - resize');
  });
} else if(window.addEventListener) {
  window.addEventListener('resize', function(event) {
    console.log('addEventListener - resize');
  }, true);
}

if (!event) {
  event = window.event;
}
var target = (event.target) ? event.target : event.srcElement;

event.clientX, 
event.clientY, 
event.currentTarget, 
event.detail, 
event.eventPhase, 
event.explicitOriginalTarget, 
event.layerX
event.layerY
event.originalTarget
event.pageX
event.pageY
event.relatedTarget
event.screenX
event.screenY
event.target
event.preventDefault
event.stopPropagation

To cancel bubbling:

event.returnValue = false;
event.cancelBubble = true;
return false;

document.getElementById("MyElement").
  addEventListener( 'click' , listener, useCapture );

There are 3 event types related to keyboard keys: keydown, keyup, keypress.

The keydown event fires when a key is depressed by the user, and it keeps on 
firing as long as the user keeps it depressed.

The keypress event is basically the same, except that it fires only when a 
character key is depressed – in other words, a key that will lead to a character 
being inserted into, say, a textarea.

The keyup event fires when the user releases the key.

Just to make absolutely sure that everybody understands – if I press, say, an 
‘o’ key, or an ‘i’ key, or one of these strange bracket keys, both a keydown and 
a keypress event will fire. On the other hand, if I press special keys such as 
the shift key, or the arrow keys, only a keydown event will fire.

This theory of the difference between keydown and keypress originated with 
Microsoft. All the Internet Explorer versions actually use this difference 
between keydown and keypress. And Safari has copied it, as from version 3.1, 
I think, which was released about a year ago, maybe slightly more. The point is, 
here, that this theory is the only theory about the difference between keydown 
and keypress in existence. In contrast, Opera and Firefox just fire lots of 
events at you all the time, because it is tradition that it is both a keydown 
and a keypress event, so we should fire both whenever we see an opportunity. 
Which is fine, but it doesn’t explain why there should be two events, instead of 
just one: the keydown event. So that’s why I kind of like this theory of the 
difference between keydown and keypress.

Keydown fires when a key – any key – is depressed. Keypress fires when a 
character key is depressed.

Device dependent event: click, mouseover, mouseout, mousemove, keyup, keydown,
keypress.  These are associated with a device.

Interface event: form submission, blur, focus, load, change.  These are not
associated with or generated by a device.

Interface events do not bubble up.

To use event delegation, we use a work-around (for interface events, which do
not bubble up).  The work around centers on event capturing, instead of event 
bubbling. Event capturing is the exact opposite of event bubbling. And it is 
supported in all standards complying browsers, excluding IE.

If you capture a focus event, event handlers on the target element’s ancestors 
are executed.  To use event capturing (not supported by IE), we use 
addEventListener and we give the last argument as true, which means that this 
event fires in capturing phase.

IE does not support event capturing, but fortunately, it supports the 
proprietary focusin and focusout events. Basically, these events are exactly 
the same as focus and blur, except that they do bubble up. So for IE’s sake, we 
add these two lines: dropdown.onfocusin, and dropdown.onfocusout. And now, 
magically, our events and delegation of the focus events, works in all browsers. 
So this is something you should know about.

What are the events supported by the browser?

onabort
onactivate
onafterprint
onafterupdate
onbeforeactivate
onbeforecopy
onbeforecut
onbeforedeactivate
onbeforeeditfocus
onbeforepaste
onbeforeprint
onbeforeunload
onbeforeupdate
onblur
onbounce
oncellchange
onchange
onclick
oncontextmenu
oncontrolselect
oncopy
oncut
ondataavailable
ondatasetchanged
ondatasetcomplete
ondblclick
ondeactivate
ondrag
ondragend
ondragenter
ondragleave
ondragover
ondragstart
ondrop
onerror
onerrorupdate
onfilterchange
onfinish
onfocus
onfocusin
onfocusout
onhashchange
onhelp
oninput
onkeydown
onkeypress
onkeyup
onload
onlosecapture
onmessage
onmousedown
onmouseenter
onmouseleave
onmousemove
onmouseout
onmouseover
onmouseup
onmousewheel
onmove
onmoveend
onmovestart
onoffline
ononline
onpaste
onpropertychange
onreadystatechange
onreset
onresize
onresizeend
onresizestart
onrowenter
onrowexit
onrowsdelete
onrowsinserted
onscroll
onsearch
onselect
onselectionchange
onselectstart
onstart
onstop
onsubmit
onunload

What is event bubbling and what is event capturing?

With event bubbling, the event is first trigger at the the target element, and then it bubble up to the root node. We had event bubbling since DOM Level 0. DOM Level 2 add an additional phase, the capture phase known as event capturing. Under DOM Level 2, when an event is triggered, the event first propagates from the root node down to the target element and then propagates again from the target element up to the root node. The former phase (root to target) is called the capture phase, and the latter phase (target to root) is called the bubble phase.

How can we register an event handler using the DOM Level 0 approach?

element.onclick = function() {};
<a href="#" onclick="functionName(someParameter,...)">..</a>

When an event handler is fired, an instance of a class named Event is passed to the handler as its first parameter in most browsers. Internet Explorer, always does things in its own proprietary way by tacking the Event instance onto the window object under the named 'event'. In order to deal with this discrepancy, we often use the following code as the first statement in the event handler:

if (!event) {
  event = window.event;
}
var target = (event.target) ? event.target : event.srcElement;

How can we use addEventListener?

document.getElementById("MyElement").addEventListener( 'click' , listener, useCapture );

$(function(){
  var element = $('#vstar')[0];
  element.addEventListener('click', function(event) { ...}, false);
});

Does Internet Explorer support event capturing?

No.

How can we use attachEvent?

if(window.attachEvent) {
    window.attachEvent('onresize', function() {
        alert('attachEvent - resize');
    });
}
else if(window.addEventListener) {
    window.addEventListener('resize', function() {
        console.log('addEventListener - resize');
    }, true);
}

Rather than addEventListener(), Internet Explorer defines a method named attachEvent() for each DOM elment. This method accepts two parameters:

attachEvent(eventName, handler)

How can we simulate a event?

For IE, use:

var e = document.createEventObject(); 
e.keyCode = 122;
element.fireEvent('onkeypress',e);

For other browsers, look for document.createEvent or use:

var event = new Event('change');
theForm.elements[i].dispatchEvent(event);

How can we correctly install handler (in a loop)?

selObj.onchange = function (i) {
    return function () {
        dynamicOptionListObjects[i].change(this);

    };
}(dol.index);

In the above code, onchange is not simply assigned a function. That function is accompanied by parantheses with parameters, and therefore that function is immediately invoked, and onchange is assigned the result of that invocation, which is a function.

How can we assign event handler (the old way)?

document.myform.onsubmit = function(){
    alert('handled');
    return false;
}

<input type="button" name="..." value="..." onclick="alert('Hello');"/>

For raw DOM event handling, how can we obtain the event object and how can we examine the event object?

I NEED TO COMPLETE THIS.

What are the 3 key events?

  1. keydown
  2. keyup
  3. keypress

What is the difference between keydown and keypress?

There are three key events – keydown, keypress, and keyup)

  • The keydown event fires when a key is depressed by the user, and it keeps on firing as long as the user keeps it depressed.
  • The keypress event is basically the same, except that it fires only when a character key is depressed – in other words, a key that will lead to a character being inserted into, say, a textarea.
  • The keyup event fires when the user releases the key.

Just to make absolutely sure that everybody understands – if I press, say, an ‘o’ key, or an ‘i’ key, or one of these strange bracket keys, both a keydown and a keypress event will fire. On the other hand, if I press special keys such as the shift key, or the arrow keys, only a keydown event will fire.

This theory of the difference between keydown and keypress originated with Microsoft. All the Internet Explorer versions actually use this difference between keydown and keypress. And Safari has copied it, as from version 3.1, I think, which was released about a year ago, maybe slightly more. The point is, here, that this theory is the only theory about the difference between keydown and keypress in existence. In contrast, Opera and Firefox just fire lots of events at you all the time, because it is tradition that it is both a keydown and a keypress event, so we should fire both whenever we see an opportunity. Which is fine, but it doesn’t explain why there should be two events, instead of just one: the keydown event. So that’s why I kind of like this theory of the difference between keydown and keypress.

Keydown fires when a key – any key – is depressed. Keypress fires when a character key is depressed.

What are the purposes of the keyCode and charCode properties?

There are two properties that any key event carries (keyCode, and charCode). The key code is the actual code of the physical key the user depresses, and the character code is the code of the resulting character. So, if I press an ‘a’ key, I get key code 65, because the ‘a’ key has the code 65. But the character code is 97, for a lower case ‘a’. If I press a shift key, I get key code 16, because that’s shift – but I do not get a character code, because the shift key, by itself, doesn’t result in any character.

The keyCode property. With a keydown event, onkeydown, it contains the key code – the code of the physical key the user depresses.

Onkeypress, on the other hand, contains the character code – basically, the ASCII code of the character that appears on the screen. And this works in all browsers – except that in Firefox, onkeypress shows zero for key code; don’t ask me why. Then, charCode. Onkeydown, charCode returns zero, and onkeypress, charCode returns the character code. And this, too, works only in Firefox and Safari, because these are the only browsers to support charCode.

If you need the actual key that the user depressed, the physical key, use the keydown event and ask for the keyCode. That will work in all browsers.

On the other hand, if you needed the character the user has just entered in a text area, or whatever, you should use the keypress event, and ask for either keyCode or charCode – one of them will contain the information you’re looking for in the browser.

What are the problems with the change event, and how can we work around those problems?

In theory, the change event would be absolutely wonderful to have, because the change event fires when the value of the form field is changed. Often, you want to detect everything the user does in a form. But usually, we are forced to use the focus or blur events instead – or maybe the click event, in the case of detecting a checkbox changes – because the change event doesn’t work quite correctly.

We’re to distinguish three different cases:

  • the change event on text fields
  • the change event on select boxes
  • the change event on checkboxes and radios.

Suppose the user focuses on a text field, in any way, either by the mouse or the keyboard, and then blurs again. In other words, he moves on to the next field. In that case, no change fires, because there’s nothing that has changed – the value of the text field has not been modified. But if we change it slightly – if we say the user focuses on the text field, and then enters something, then blurs the text field, then a change event fires at the moment the user blurs the text field. Because the value of the text field has been modified, and that obviously causes a change event. This is all good; this works perfectly in all browsers.

However, when we get to select boxes, we start to encounter some difficulties. The change event of select boxes is, of course, about the oldest JavaScript event you can think of. We’ve been using the change event for ages, and it works, provided you use a mouse. With a mouse, it’s all pretty simple. The first click on the select box opens up all the options, and the second click selects a new option – and as soon as a new option has been selected, a change event fires. This works in all browsers.

The user also has a way to use the keyboard to enter select boxes, and then the situation gets much more complicated. The first step the user has to take, obviously, is focusing on the select box. Then he can use the arrow keys to go through the options and select the one he wants. Which is all fine, except that as soon as the user presses an arrow key once, a change event fires in IE and Opera. Suppose you have a list of, say, twenty options, and the user wants to select the twentieth one – then he has to go through the actual list option by option, presses the arrow key nineteen times, and a change event fires nineteen times.

Firefox and Safari allow the user to use the arrow keys to scroll through the select box. And only when the user blurs the select box then a change event is fired.

When we come to checkboxes and radios it becomes even worse. A click on a checkbox – and I do not mean necessarily a mouse click, but an activate event can be fired either by the mouse, or by the keyboard. A click event on a checkbox, of course, changes the value of the check property – goes from true to false, or vice versa – and what should happen is that a change event fires right then and there, because the user has actually changed something. And a change event does fire in Firefox, Safari, and Opera, but not in IE.

What happens in IE? You click on this checkbox; nothing happens. What’s going on? You first have to blur the checkbox. You have to go somewhere else, either with your mouse or with your keyboard. And only when the checkbox has been blurred, then the change event fires. Which is, of course, totally horrible for any sort of interface that wants to use a lot of checkboxes – for instance, to fold stuff out or in, the user wants to check this checkbox, and immediately the thing he expects folds out, or folds in. And this IE bug means that we cannot use the change event for this – we have to use a click event. That’s not such a terrible problem, but it’s once again a pretty annoying bug in IE.

The event specification only talks about blurring, as according to the event specification, a change event should fire when a certain form field has been changed, and is blurred. And as we saw right now, that makes perfect sense for text fields; it makes perfect sense for select boxes when we used a keyboard; but it does not make sense for checkboxes or radios, or for select boxes when you use the mouse.

What is event bubbling and what is event capturing?

I NEED TO COMPLETE THIS.

Which browsers support event capturing and which browsers support event bubbling?

Event capturing is supported by all standard-compliant browsers, except IE, which support event bubbling.

What is event delegation?

Event delegation is a way of defining less event handlers. What we do in event delegation is make use of the fact that many events bubble up. That is, as soon as the user mouse is over a link, the mouseover event, if any, on the link itself, fires – and then the event bubbles up all the way to the document level, triggers any event handler for the mouseover on the ‘li’, on the ‘ul’, etc, etc. All the way up to the document. The point here is the mouseover and the mouseout events will bubble up to the ‘ul’ anyway, so why shouldn’t we handle the event there? Basically, it saves you a lot of event handlers.

What is special about the click event?

It is device-independent. It is fired regardless whether the user use a mouse or a keyboard. The click event is the only event that fires both with mouse, and with the keyboard. If you click on a link with the mouse, the click event fires; if you move to a link by means of tabbing until the focus is on the link, and then you hit enter or the spacebar, that the click event also fires. The click event is one of the very few events that is truly device independent. So, a click event is always safe.

What is an interface event and what is a device-dependent event?

Mouse and key events are events that fire when the user initiates a device specific action. Interface events, on the other hand, they fire when a certain event takes place, regardless of how that event was initialized. The best example of that is a form submission – as soon as a form is submitted, a submit event fires, and it does not matter exactly how the user has submitted that form. It could go to the submit button with the mouse, if I click on it, or chart all the way through the form to the submit button and hit enter, or be in a text field and also hits enter, because that also submits a form. It does not matter exactly how the user submits the form, which of these three methods he chooses – a submit event will always fire. And that’s the general idea of the interface events. Other examples include load, change, focus, and blur. And, of course, we are on the hunt for focus and blur here, because we want to make our dropdown menu device independent.

Which event types do not bubble up?

The focus and blur events do not bubble up. In general, device-dependent events should bubble up all the way to the document level, and interface events do not bubble.

How can we use event delegation if certain event types do not bubble up?

In general, interface events do not bubble.

But we want to use nice event delegation. Fortunately, there is a work around. And that work around centers on event capturing, instead of event bubbling. Event capturing is the exact opposite of event bubbling. And it is supported in all standards complying browsers, excluding IE.

If you capture a focus event, event handlers on the target element’s ancestors are executed.

To use event capturing (not supported by IE), we use addEventListener and we give the last argument as true, which means that this event fires in capturing phase.

IE does not support event capturing, but fortunately, it supports the proprietary focusin and focusout events. Basically, these events are exactly the same as focus and blur, except that they do bubble up. So for IE’s sake, we add these two lines: dropdown.onfocusin, and dropdown.onfocusout. And now, magically, our events and delegation of the focus events, works in all browsers. So this is something you should know about.

What are the properties of an event object?

event.clientX, 
event.clientY, 
event.currentTarget, 
event.detail, 
event.eventPhase, 
event.explicitOriginalTarget, 
event.layerX
event.layerY
event.originalTarget
event.pageX
event.pageY
event.relatedTarget
event.screenX
event.screenY
event.target
event.preventDefault
event.stopPropagation

How can we cancel event bubbling?

event.returnValue = false;
event.cancelBubble = true;
return false;

How can we detect if the window is resized?

if(window.attachEvent) {
    window.attachEvent('onresize', function() {
        alert('attachEvent - resize');
    });
}
else if(window.addEventListener) {
    window.addEventListener('resize', function() {
        console.log('addEventListener - resize');
    }, true);
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License