Where is specified that there is a "onXYZ" in document? - javascript

I know that some browsers provide supported HID events via a definied onXYZ property in document, so that one might test e.g. for touch support by testing
if ("ontouchstart" in document) {
...
}
The question is: which specification defines that a element should contain these onXYZ properties?
This question is not about: can I use this, should I use this, which browser supports this...
I've looked through nearly all DOM, events related specifications in
http://www.w3.org/TR/tr-technology-stds
but didn't found a trace.
Update: Clarification:
I'm looking for a specification wording like this:
A browser should define a attribute named onEVENTNAME if it does trigger EVENTNAME on some event.
Interface MouseEvents:
onmousedown: null; // define to tell there is a mousedown events can can be listened to
onmouseup: null;
...
DomElement implementes MouseEvents:
...

The property on the object whose name starts with "on" followed by the event type name is called the "Event Handler IDL Attribute". Note that an Event Handler is not the same thing as an Event Listener.
Section 7.1.5.2.1 of HTML5.1 lists the Event Handler IDL Attributes and the objects to which they apply.
Note that this doesn't include the Touch interface. There's two points to take from that.
There's no requirement for there to be ontouchstart, ontouchend, etc event handlers, either in HTML5 or in the Touch Events spec, and indeed they are not necessary to use touch events, since listeners can be matched with the event types using addEventListener.
There's nothing that precludes a new or updated spec from adding a requirement for event handlers for such events, nor from browsers implementing such handlers in advance of them being documented in a spec.
As a consequence, if ("ontouchstart" in document) is not a good test. Maybe a better way of testing for touch support would be creating a TouchEvent and checking its type.
Incidentally, contrast the Touch events spec, which doesn't mention event handlers, with the more hardware agnostic Pointer events spec which does provide a list of event handlers for pointer events

Related

Why deleting event listeners, ever?

From the Polymer documentation about event listeners:
Use automatic node finding and the convenience methods listen and > unlisten.
this.listen(this.$.myButton, 'tap', 'onTap');
this.unlisten(this.$.myButton, 'tap', 'onTap');
The listener callbacks are invoked with this set to the element instance.
If you add a listener imperatively, you need to remove it imperatively. This is commonly done in the attached and detached callbacks. If you use the listeners object or annotated event listeners, Polymer automatically adds and removes the event listeners.
Questions:
Why is it important to only listen to events of elements in the local DOM after attached(), to then remove them when detached()?
Aren't event listeners deleted automatically when the observed DOM object is destroyed?
Would this also apply to when you listen to events for elements in your light DOM?
Basically, it's just best practise. Older browsers don't handle removal of old events correctly, and if functions have scope references they can cause memory leaks. I guess it's a convention along the lines of "better safe than sorry."
Polymer only removes event listeners it added itself. If you add event listeners yourself (imperatively) you need to remove them yourself.
Code might not be able to get garbage collected if event listeners are referring code.

Bubbling and Capturing in context of addEventListener() method in javascript

in addEventListner(event,function,useCapture) method, useCapture parameter is two type bubbling and capturing.
My question is what is the function/operation of this useCapture parameter in context of js addEventListener() method?
This diagram from the DOM events specification may help shed some light:
As you can see from that, there are three phases to an event: The capturing phase, which originates at the very top level view and works its way down to the descendant element the event is aimed at, then the target phase which occurs just on the target element, and finally the bubbling phase where it goes back up the hierarchy back to the root view.
The vast majority of the time, you only need or want to work with the bubbling phase (and IE didn't even support the capturing phase until IE9). Whether this is necessarily because it's more useful is a question; we're all just really used to it, and it's been the focus of continued innovation (cancelling bubbling and such), because (again) for years and years it was the only game in town if you wanted to support IE. And it does make good sense, but then, so does capturing.
The reason this exists is primarily a quirk of history. Very early on, of course, there were not specifications for this, and the dominant browsers at the time (Netscape Navigator and Microsoft Internet Explorer) both made up what they did with events. Netscape went with the "starts at the root and makes its way to the final target" (capturing) approach, Microsoft went with the "starts at the target and works its way to the root" (bubbling) approach. So when it came time to standardize this, the DOM committee decided to go with...both.
The third parameter(useCapture) of the addEventListener() method is decided in which way
the event is propagated in the html DOM.
this parameter has an boolean value,false indicates bubbling and true indicates capturing.
It is optional parameter and its default value is false.
Event propagation is a way of defining the element order when an event occurs.
Suppose you have a h1 element inside a div element.Now if user clicks the h1 element,
then which element's "click" event will be handled first?
In bubbling the inner most element's event will be handle first then the outer.
i.e.h1 element's "click" event will be handled first, then the div element's event will be handled.
In capturing the outer most element's event will be handle first then the inner.
i.e.div element's "click" event will be handled first, then the h1 element's event will be handled.

DOM: Is it possible for user interaction to occur on anything but an element node?

In the W3C browser spec, there's a lot of user interaction events. Keypress, click, mouse move, etc.
Most of which occur on the window object (mousemove), but some of which occur on elements (click).
Is there any time an event occurs on anything but the window object or an element?
For instance, is it possible for a click event to be dispatched on a text node by the browser?
Is there a list of which node types correspond with which event types?
Is there any time an event occurs on anything but the window object or an element?
DOM 3 Event Types can occur on document and defaultView objects and there is a long list of Legacy Event Types that can occur on a much wider range of node types.
While the vast majority of DOM 3 events have an element as their event target, it should not be assumed that the event target is always an element. Any type of node can dispatch an event (i.e. can be an event target). Of the 12 node types for Interface Node, 11 aren't an element.
The W3C DOM specifications define the types of event associated with various types of node, but that does not limit the type of node that can be an event target:
Note: Though an event listener can be registered for any event target
node, the user agent only dispatches UA-generated (trusted) events on
node types that are defined as event target types for that specific
event type (see the List of DOM3 Event Types). For example, a
mouseover event type registered on a text node will never be fired by
the user agent, though a content author could dispatch an event of
that type on the text node via script.
Document Object Model (DOM) Level 3 Events Specification (Draft) §4.3
So even if the W3C doesn't specify standard events for non–element nodes, they may in the future and content authors (developers) can dispatch events from non–element nodes already (and have been able to do that for some time).
Also, browsers are not constrained to only those events in the W3C specifications, they can do what they like.
is it possible for a click event to be dispatched on a text node by the browser
Yes, and early versions of Safari did just that. However is was not conformant with other browsers so it was changed to comply with common behaviour.

Difference between document.addEventListener and window.addEventListener?

While using PhoneGap, it has some default JavaScript code that uses document.addEventListener, but I have my own code which uses window.addEventListener:
function onBodyLoad(){
document.addEventListener("deviceready", onDeviceReady, false);
document.addEventListener("touchmove", preventBehavior, false);
window.addEventListener('shake', shakeEventDidOccur, false);
}
What is the difference and which is better to use?
The document and window are different objects and they have some different events. Using addEventListener() on them listens to events destined for a different object. You should use the one that actually has the event you are interested in.
For example, there is a "resize" event on the window object that is not on the document object.
For example, the "readystatechange" event is only on the document object.
So basically, you need to know which object receives the event you are interested in and use .addEventListener() on that particular object.
Here's an interesting chart that shows which types of objects create which types of events: https://developer.mozilla.org/en-US/docs/DOM/DOM_event_reference
If you are listening to a propagated event (such as the click event), then you can listen for that event on either the document object or the window object. The only main difference for propagated events is in timing. The event will hit the document object before the window object since it occurs first in the hierarchy, but that difference is usually immaterial so you can pick either. I find it generally better to pick the closest object to the source of the event that meets your needs when handling propagated events. That would suggest that you pick document over window when either will work. But, I'd often move even closer to the source and use document.body or even some closer common parent in the document (if possible).
The window binding refers to a built-in object provided by the browser. It represents the browser window that contains the document. Calling its addEventListener method registers the second argument (callback function) to be called whenever the event described by its first argument occurs.
<p>Some paragraph.</p>
<script>
window.addEventListener("click", () => {
console.log("Test");
});
</script>
Following points should be noted before select window or document to addEventListners
Most of the events are same for window or document but
some events like resize, and other events related to loading,
unloading, and opening/closing should all be set on the window.
Since window has the document it is good practice to use document to
handle (if it can handle) since event will hit document first.
Internet Explorer doesn't respond to many events registered on the
window,so you will need to use document for registering event.
You'll find that in javascript, there are usually many different ways to do the same thing or find the same information. In your example, you are looking for some element that is guaranteed to always exist. window and document both fit the bill (with just a few differences).
From mozilla dev network:
addEventListener() registers a single event listener on a single
target. The event target may be a single element in a document, the
document itself, a window, or an XMLHttpRequest.
So as long as you can count on your "target" always being there, the only difference is what events you're listening for, so just use your favorite.
In my opinion, it is generally better to pick the closest object to the source of the event that meets your needs when handling propagated events.
So, if you want the event to happen to the element, it's better to use window.addEventListener() (assume the window variable is an element) because the most important thing here when listening to an event is that the code and event execution work faster: the only thing that matters in this case.

Event Capturing vs Event Bubbling [duplicate]

This question already has answers here:
What is event bubbling and capturing?
(9 answers)
Closed 2 years ago.
I just wanted to get the general consensus on which is a better mode of event delegation in JS between bubbling and capturing.
Now I understand that depending on a particular use-case, one might want to use capturing phase over bubbling or vice versa but I want to understand what delegation mode is preferred for most general cases and why (to me it seems bubbling mode).
Or to put it in other words, is there a reason behind W3C addEventListener implementation to favor the bubbling mode. [capturing is initiated only when you specify the 3rd parameter and its true. However, you can forget that 3rd param and bubbling mode is kicked in]
I looked up the JQuery's bind function to get an answer to my question and it seems it doesn't even support events in capture phase (it seems to me because of IE not support capturing mode).
So looks like bubbling mode is the default choice but why?
In the past it was a platform issue, Internet Explorer had a bubbling model, and Netscape was more about capturing (yet supported both).
The W3C model calls for you be able to choose which one you want.
I think bubbling is more popular because, as stated there are some platforms that only support bubbling...and it sort of makes sense as a "default" mode.
Which one you choose is largely a product of what you are doing and what makes sense to you.
While reading JavaScript: The Definitive Guide, 5th Edition, I came across Example 17-4 on page 422 that defines a function for dragging absolutely positioned elements. In the example, the function drag() is called in the onmousedown attribute of a document element. The function repositions the element based on the change in location of the mouse which is queried by handlers added to the root document element for captured mousemove and mouseup events. They capture these events on the document for the following reason:
It is important to note that the mousemove and mouseup handlers are registered as capturing event handlers because the user may move the mouse faster than the document element can follow it, and some of these events occur outside the original target element.
This suggests an advantage in quicker response when capturing events.
This test suggests there is a slight performance advantage to using capture over bubble. Even without killing the event as soon as it is handled, however when left it was marginal. I suppose a complex DOM would exaggerate the performance difference between the two.
This link gives the clear explanation- https://www.quirksmode.org/js/events_order.html
You, the web developer, can choose whether to register an event handler in the capturing or in the bubbling phase. This is done through the addEventListener() method explained on the Advanced models page. If its last argument is true the event handler is set for the capturing phase, if it is false the event handler is set for the bubbling phase.
Suppose you do
element1.addEventListener('click',doSomething2,true)
element2.addEventListener('click',doSomething,false)
If the user clicks on element2 the following happens:
The click event starts in the capturing phase. The event looks if any ancestor element of element2 has a onclick event handler for the capturing phase.
The event finds one on element1. doSomething2() is executed.
The event travels down to the target itself, no more event handlers for the capturing phase are found. The event moves to its bubbling phase and executes doSomething(), which is registered to element2 for the bubbling phase.
The event travels upwards again and checks if any ancestor element of the target has an event handler for the bubbling phase. This is not the case, so nothing happens.
The reverse would be
element1.addEventListener('click',doSomething2,false)
element2.addEventListener('click',doSomething,false)
Now if the user clicks on element2 the following happens:
The click event starts in the capturing phase. The event looks if any ancestor element of element2 has a onclick event handler for the capturing phase and doesn’t find any.
The event travels down to the target itself. The event moves to its bubbling phase and executes doSomething(), which is registered to element2 for the bubbling phase.
The event travels upwards again and checks if any ancestor element of the target has an event handler for the bubbling phase.
The event finds one on element1. Now doSomething2() is executed.
Compatibility with traditional model
In the browsers that support the W3C DOM, a traditional event registration
element1.onclick = doSomething2;
is seen as a registration in the bubbling phase.
Use of event bubbling
Few web developers consciously use event capturing or bubbling. In Web pages as they are made today, it is simply not necessary to let a bubbling event be handled by several different event handlers. Users might get confused by several things happening after one mouse click, and usually you want to keep your event handling scripts separated. When the user clicks on an element, something happens, when he clicks on another element, something else happens.
Of course this might change in the future, and it’s good to have models available that are forward compatible. But the main practical use of event capturing and bubbling today is the registration of default functions.
I'm not certain but I'm pretty sure that anything you can do with bubbling you can do with capturing and vice versa.
The idea that you'd have some events bubbling and some capturing in the same app sounds like a good way to make things very confusing. What I'm saying is, I don't think bubbling versus capturing really matters. What matters is that you pick one and stick with it.
W3C's APIs often contain this sort of thing where they have a lot of features that nobody really cares about. Perhaps this is another example of how good defaults can remove the need for configuration or even whole features.

Categories

Resources