,
The handlers are the same as before, but this time - at the immersion stage. Well, to see the interception in action, click on the element in it.
The handlers will fire in the order "from top to bottom": FORM → DIV → P.
The JS code here is like this:
Var elems = document.querySelectorAll ("form, div, p"); // hang up a handler for each element at the interception stage for (var i = 0; i< elems.length; i++) {
elems[i].addEventListener("click", highlightThis, true);
}
Nobody bothers you to assign handlers for both stages, like this:
Var elems = document.querySelectorAll ("form, div, p"); for (var i = 0; i< elems.length; i++) {
elems[i].addEventListener("click", highlightThis, true);
elems[i].addEventListener("click", highlightThis, false);
}
Click on the inner element
To see the order of the event:
It should be FORM -> DIV -> P -> P -> DIV -> FORM. Note that the element
Will participate in both stages.
Outcomes
- When an event occurs - the element on which the event occurred is marked as event.target.
- The event first moves down from the document root to event.target, invoking the handlers supplied via addEventListener (…., True) along the way.
- The event moves from event.target up to the beginning of the document, along the way it calls the handlers supplied via addEventListener (…., False).
Each handler will have access to the properties of the event:
- event.target is the deepest element where the event actually happened.
- event.currentTarget (= this) - the element on which the self-handler has triggered at the moment (to which the event has "reached").
- event.eventPhase - in which phase the event handler was triggered (immersion = 1, bubbling = 3).
The bubbling can be stopped by calling the event.stopPropagation () method, but it is not recommended to do this, since you may need the event for the most unexpected purposes.
Interception of an event
One of the important features of the language is event interception. If someone, for example, clicks on a button, the onClick event handler corresponding to that button is called. With the help of event handling, you can ensure that the object corresponding to your window, document or layer intercepts and processes the event even before the event handler is called by the object of the specified button for this purpose. Likewise, an object in your window, document, or layer can process an event signal even before it reaches its normal destination.
To see what this can be useful for, let's look at the following example:
Click on this link
As you can see, we do not specify event handling programs in the tag ... Instead, we write
window.captureEvents (Event.CLICK);
in order to intercept the event Click window object. Usually the window object does not work with the event Click... However, after intercepting, we then redirect it to the window object. Note that in Event.CLICK fragment CLICK must be written in capital letters. If you want to intercept several events, then you should separate them from each other with | symbols. For example:
window.captureEvents (Event.CLICK | Event.MOVE);
In addition, in the function handle () assigned by us to the role of the event handler, we use the instruction return true;... What this really means is that the browser has to process the link itself after the function finishes. handle ()... If you write instead return false; then it will all end there.
If now in the tag
You will define the event handler onClick, you will understand that this program will not be called when this event occurs. This is not surprising, since the window object catches the event signal even before it reaches the link object. If you define a function handle () how
function handle (e) (
alert ("The window object captured this event!");
window.routeEvent (e);
return true;
}
then the computer will check to see if other event handlers have been defined for this object. The variable e is our Event object, which is passed to the event handling function as an argument.
In addition, you can directly send an event signal to an object. To do this, you can use the method handleEvent ()... It looks like this:
window.captureEvents(Event.CLICK);
window.onclick= handle;
function handle(e) {
document.links.handleEvent(e);
}
Click on this link
onClick = "alert (" Event handler for the second link! ");"> Second link
All signals about Click events are sent for processing via the second link - even if you haven't clicked on any of the links at all!
The following script demonstrates how your script can respond to keystroke signals. Click on a key and see how this script works.
window.captureEvents(Event.KEYPRESS);
window.onkeypress= pressed;
function pressed(e) {
alert("Key pressed! ASCII-value: " + e.which);
}
На этом уроке мы познакомимся с таким понятием как всплытие события, а также рассмотрим, как его можно прервать. Кроме этого выясним, какие ещё этапы (фазы) проходит событие, перед тем как начать всплывать.
Всплытие события
Если у некоторого элемента возникает событие, то оно начинает "всплывать", т.е. возникает у родителя, потом у прародителя и т.д.
Из этого следует, что событие, которое сгенерировал некоторый элемент, можно перехватить с помощью обработчика на родителе, прародителе и т.д.
Всплытие события (пузырька) продемонстрируем на следующем примере:
Заголовок
Некоторый очень важный текст
Раздел
Некоторый текст
Остальной текст
Напишем небольшой скрипт, с помощью которого добавим обработчик события " click " для всех элементов страницы, а также для объектов document и window .
Let's create an HTML page and paste the above HTML code into it. Let's insert the script, written in JavaScript, before the closing body tag. After that, open the newly created page in a web browser, press the F12 key and go to the console. Now let's left-click in the area belonging to the strong element and see how the event will bubble up.
How to interrupt bubbling of an event
The bubbling of an event (bubble) can be interrupted. In this case, this event will not be triggered for parent (parent) elements. The method that is designed to stop the bubbling event (bubble) is called stopPropagation ().
For example, let's change our example above so that the event doesn't pop up above the body: