-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEvent
240 lines (193 loc) · 8.1 KB
/
Event
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
In JavaScript, **events** are actions or occurrences that happen in the browser that you can respond to in your code. Events can be triggered by user interactions, such as clicking a button or pressing a key, or they can be generated by the browser itself, such as when a page loads or an image is finished loading.
### Key Concepts of Events
1. **Event Types**:
Events can be broadly categorized into several types:
- **Mouse Events**: Triggered by mouse actions, such as `click`, `dblclick`, `mouseover`, `mouseout`, `mousedown`, and `mouseup`.
- **Keyboard Events**: Triggered by keyboard actions, such as `keydown`, `keyup`, and `keypress`.
- **Form Events**: Related to user input in forms, such as `submit`, `change`, `input`, `focus`, and `blur`.
- **Window Events**: Triggered by actions related to the browser window, such as `load`, `resize`, `scroll`, and `unload`.
- **Touch Events**: Relevant for touch devices, such as `touchstart`, `touchmove`, `touchend`, and `touchcancel`.
2. **Event Target**:
- The **event target** is the element that triggered the event. You can access it through the `event.target` property in the event handler.
3. **Event Bubbling and Capturing**:
- **Bubbling**: Events propagate from the target element up to the root of the document. For example, if a child element is clicked, the event will bubble up to its parent and then to the grandparent, and so on.
- **Capturing**: Events can also be captured from the root down to the target element, although this is less commonly used.
4. **Event Object**:
- When an event occurs, an event object is created and passed to the event handler. This object contains properties and methods related to the event, such as `type`, `target`, and methods like `preventDefault()` and `stopPropagation()`.
### Working with Events
To work with events in JavaScript, you typically use methods like `addEventListener` to attach event handlers to elements.
#### Example
Here’s a simple example that demonstrates how to handle a click event:
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event Example</title>
</head>
<body>
<button id="myButton">Click Me!</button>
<p id="message"></p>
<script>
// Select the button and message paragraph
const button = document.getElementById('myButton');
const message = document.getElementById('message');
// Define the event handler
function showMessage(event) {
message.textContent = "Button clicked!";
console.log("Event type: " + event.type); // Logs the type of event
}
// Attach the click event listener
button.addEventListener('click', showMessage);
</script>
</body>
</html>
```
### Summary
Events are a fundamental concept in JavaScript, allowing developers to create dynamic and interactive web applications. By responding to various user actions and browser events, you can enhance the user experience significantly.
If you have any more specific questions about events or need further examples, feel free to ask!
_---------------------------------------------------------------------
Sure! Let's dive deeper into events in JavaScript, covering various event-related methods, their functionalities, and examples for better understanding.
### 1. **addEventListener**
- **Description**: Attaches an event handler to a specified element.
- **Syntax**:
```javascript
element.addEventListener(event, handler, options);
```
- **Example**:
```html
<button id="myButton">Click Me!</button>
<script>
const button = document.getElementById('myButton');
button.addEventListener('click', () => {
alert('Button was clicked!');
});
</script>
```
### 2. **removeEventListener**
- **Description**: Removes an event handler that was attached with `addEventListener`.
- **Syntax**:
```javascript
element.removeEventListener(event, handler, options);
```
- **Example**:
```html
<button id="myButton">Click Me!</button>
<script>
const button = document.getElementById('myButton');
function handleClick() {
alert('Button was clicked!');
}
button.addEventListener('click', handleClick);
button.removeEventListener('click', handleClick); // Now the event won't trigger
</script>
```
### 3. **dispatchEvent**
- **Description**: Dispatches an event to the specified element, triggering any event handlers that are listening for that event.
- **Syntax**:
```javascript
element.dispatchEvent(event);
```
- **Example**:
```html
<button id="myButton">Click Me!</button>
<script>
const button = document.getElementById('myButton');
const event = new Event('customEvent');
button.addEventListener('customEvent', () => {
alert('Custom event triggered!');
});
// Dispatch the custom event
button.dispatchEvent(event);
</script>
```
### 4. **Event Object Properties**
When an event occurs, an event object is created. Common properties include:
- **type**: The type of the event (e.g., `"click"`).
- **target**: The element that triggered the event.
- **currentTarget**: The element to which the event handler is attached.
- **bubbles**: Indicates if the event bubbles up through the DOM.
- **cancelable**: Indicates if the event can be canceled.
**Example**:
```html
<button id="myButton">Click Me!</button>
<script>
const button = document.getElementById('myButton');
button.addEventListener('click', (event) => {
console.log('Event type:', event.type);
console.log('Target:', event.target);
});
</script>
```
### 5. **Event Methods**
- **preventDefault()**: Prevents the default action associated with the event (e.g., preventing a form from submitting).
- **stopPropagation()**: Stops the event from bubbling up to parent elements.
- **stopImmediatePropagation()**: Prevents the event from propagating and stops other handlers from being executed.
**Example**:
```html
<form id="myForm">
<input type="submit" value="Submit">
</form>
<script>
const form = document.getElementById('myForm');
form.addEventListener('submit', (event) => {
event.preventDefault(); // Prevents the form from submitting
alert('Form submission prevented!');
});
</script>
```
### 6. **Event Types**
Common event types you can listen for:
- **Mouse Events**:
- `click`, `dblclick`, `mouseover`, `mouseout`, `mousedown`, `mouseup`.
**Example**:
```html
<div id="myDiv" style="width: 100px; height: 100px; background: red;"></div>
<script>
const div = document.getElementById('myDiv');
div.addEventListener('mouseover', () => {
div.style.background = 'blue';
});
div.addEventListener('mouseout', () => {
div.style.background = 'red';
});
</script>
```
- **Keyboard Events**:
- `keydown`, `keyup`, `keypress`.
**Example**:
```html
<input type="text" id="myInput">
<script>
const input = document.getElementById('myInput');
input.addEventListener('keydown', (event) => {
console.log('Key pressed:', event.key);
});
</script>
```
- **Form Events**:
- `submit`, `change`, `input`, `focus`, `blur`.
**Example**:
```html
<input type="text" id="textInput">
<script>
const textInput = document.getElementById('textInput');
textInput.addEventListener('input', () => {
console.log('Input value changed:', textInput.value);
});
</script>
```
- **Window Events**:
- `load`, `resize`, `scroll`, `unload`.
**Example**:
```html
<script>
window.addEventListener('resize', () => {
console.log('Window resized!');
});
</script>
```
### Summary
These methods and properties provide a powerful way to handle events in JavaScript, allowing you to create responsive and interactive web applications. By understanding and using `addEventListener`, `removeEventListener`, and event object properties, you can effectively manage user interactions and other events.
If you have more questions or need further examples on specific topics, feel free to ask!