-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheventbubbling.html
More file actions
64 lines (45 loc) · 1.8 KB
/
eventbubbling.html
File metadata and controls
64 lines (45 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<!-- Event bubbling -->
<!-- When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors.
Let’s say we have 3 nested elements FORM > DIV > P with a handler on each of them: -->
<!DOCTYPE html>
<html>
<head>
<style>
body * {
margin: 10px;
border: 1px solid blue;
}
</style>
</head>
<body>
<form onclick="alert('form')">FORM
<div onclick="alert('div')">DIV
<p onclick="alert('p')">P</p>
</div>
</form>
</body>
</html>
<!-- A click on the inner <p> first runs onclick:
On that <p>.
Then on the outer <div>.
Then on the outer <form>.
And so on upwards till the document object -->
<!-- So if we click on <p>, then we’ll see 3 alerts: p → div → form.
The process is called “bubbling”, because events “bubble” from the inner element up through parents like a bubble in the water -->
<!-- What Happens When You Click on <p>:
When you click on the <p> element:
The onclick for <p> runs → alert 'p'
Then the event bubbles up to the parent <div> → alert 'div'
Then it bubbles up again to the <form> → alert 'form'
So you’ll see three alerts in order: -->
<!-- p
div
form -->
<!-- STOPPING bubbling
A bubbling event goes from the target element straight up. Normally it goes upwards till <html>, and then to document object, and some events even reach window, calling all handlers on the path.
But any handler may decide that the event has been fully processed and stop the bubbling.
The method for it is event.stopPropagation().
For instance, here body.onclick doesn’t work if you click on <button>: -->
<body onclick="alert(`the bubbling doesn't reach here`)">
<button onclick="event.stopPropagation()">Click me</button>
</body>