Join Regular Classroom : Visit ClassroomTech

JavaScript – codewindow.in

Related Topics

HTML

Introduction
Html page 1
Html page 2
Html page3
Html page4

HTML Elements and structure
Html page 5
Html page 6
Html page 7

HTML Headings and Paragraphs
Html page 8
Html page 9
Html page 10

HTML Lists and Tables
Html page 11
Html page 12
Html page 13

HTML Forms and Input Fields
Html page 14
Html page 15
Html page 16

HTML Images and Media
Html page 17
Html page 18

HTML Links and Anchors
Html page 19
Html page 20
Html page 21

HTML Styles and Formatting
Html page 22

HTML Semantic Elements
Html page 23
Html page 24

HTML Attributes
Html page 25
Html page 26

HTML JavaScript Integration
Html page 27
Html page 28
Html page 29
Html page 30

HTML Document and Browser Support
Html page 31
Html page 32

HTML5 New Elements and Attributes
Html page 33
Html page 34
Html page 35
Html page 36

HTML Accessibility and Web Standards
Html page 37
Html page 38
Html page 39

HTML Responsive Design and Mobile Devices.
Html page 40
Html page 41
Html page 42

JAVASCRIPT

<ul id="parentList">
  <!-- No list items here initially -->
</ul>
JavaScript:
const parentList = document.getElementById('parentList');

parentList.addEventListener('click', function(event) {
  if (event.target.tagName === 'LI') {
    console.log('Clicked list item:', event.target.textContent);
  }
});

// Add a new list item dynamically
const newItem = document.createElement('li');
newItem.textContent = 'New Item';
parentList.appendChild(newItem);
In this example, the event listener is attached to the ul element (parentList). When a new list item is added dynamically, the event delegation allows it to be clicked without the need to attach a separate event listener to each individual li element.
<button class="myButton">Button 1</button>
<button class="myButton">Button 2</button>
<button class="myButton">Button 3</button>
JavaScript:
const buttons = document.querySelectorAll('.myButton');

buttons.forEach(function(button) {
  button.addEventListener('click', function() {
    // 'this' refers to the button element that triggered the click event
    console.log('Clicked button:', this.textContent);

    // You can perform specific actions on the element using 'this'
    this.style.backgroundColor = 'red';
    this.disabled = true;
  });
});
In the example above, we use document.querySelectorAll('.myButton') to select all elements with the class “myButton.” Then, we use forEach to loop through each button and attach a click event listener to it. Inside the event listener function, we use this to access the button that was clicked. We log the text content of the button and change its background color to red and disable it.
Using this in event handling makes the code more reusable and dynamic because you don’t need to refer to specific element IDs or classes explicitly. Instead, you can use the context provided by this to perform actions directly on the element that triggered the event. It’s a powerful feature that simplifies event handling and encourages cleaner and more modular code.
<div id="outer">
  <div id="inner">
    <button id="myButton">Click me</button>
  </div>
</div>
const outer = document.getElementById('outer');
const inner = document.getElementById('inner');
const button = document.getElementById('myButton');

outer.addEventListener('click', function() {
  console.log('Capturing phase - Outer');
}, true);

inner.addEventListener('click', function() {
  console.log('Capturing phase - Inner');
}, true);

button.addEventListener('click', function() {
  console.log('Target phase - Button');
});

inner.addEventListener('click', function() {
  console.log('Bubbling phase - Inner');
});

outer.addEventListener('click', function() {
  console.log('Bubbling phase - Outer');
});
If you click the button in the example above, you will see the following sequence in the console:
  1. Capturing phase – Outer
  2. Capturing phase – Inner
  3. Target phase – Button
  4. Bubbling phase – Inner
  5. Bubbling phase – Outer
The capturing phase occurs first, starting from the outermost ancestor and going down to the target element. Then, the target phase executes the event handler on the target element itself. Finally, the bubbling phase occurs, starting from the target element and bubbling up through its ancestors.
Event propagation is important to understand because it can affect how you handle events, especially when you have event handlers on ancestor elements and want to control the order in which they are executed.
const button = document.getElementById('myButton');

button.addEventListener('click', function() {
  console.log('Button clicked!');
});
  1. Hover Event: The mouseover event is triggered when the mouse pointer hovers over an element.
const element = document.getElementById('myElement');

element.addEventListener('mouseover', function() {
  console.log('Mouse over the element');
});
  1. Mouseout Event: The mouseout event is triggered when the mouse pointer moves out of an element.
const element = document.getElementById('myElement');

element.addEventListener('mouseout', function() {
  console.log('Mouse left the element');
});
4. Submit Event: The submit event is triggered when a form is submitted either by clicking a submit button or by pressing the “Enter” key in an input field.
const form = document.getElementById('myForm');

form.addEventListener('submit', function(event) {
  event.preventDefault(); // Prevent form submission
  console.log('Form submitted!');
});
  1. Input Event: The input event is triggered when the value of an input field or textarea is changed by the user.
const inputField = document.getElementById('myInput');

inputField.addEventListener('input', function() {
  console.log('Input value changed:', this.value);
});
  1. Keypress Event: The keypress event is triggered when a key is pressed while an input field or textarea is in focus.
const inputField = document.getElementById('myInput');

inputField.addEventListener('keypress', function(event) {
  console.log('Key pressed:', event.key);
});
7. Focus Event: The focus event is triggered when an element gains focus, such as when an input field is clicked or receives focus programmatically.
const inputField = document.getElementById('myInput');

inputField.addEventListener('focus', function() {
  console.log('Input field focused');
});
  1. Blur Event: The blur event is triggered when an element loses focus, such as when the user clicks outside an input field.
const inputField = document.getElementById('myInput');

inputField.addEventListener('blur', function() {
  console.log('Input field lost focus');
});
These are just a few examples of commonly used events in JavaScript. There are many more events available that you can use to make your web applications interactive and responsive to user actions. Each event serves a specific purpose and can be combined with other JavaScript functionality to create rich user experiences.
document.addEventListener('keydown', function(event) {
  console.log('Key pressed:', event.key);
});
In this example, whenever a key is pressed while the document is in focus, the keydown event will be triggered, and the event listener function will log the key that was pressed in the console.
You can use the same approach with the keyup event if you want to detect the key that was released:
document.addEventListener('keyup', function(event) {
  console.log('Key released:', event.key);
});
The event.key property will provide different values depending on the key pressed. For alphanumeric keys, it will return the character that corresponds to the key. For special keys like Enter, Escape, Arrow keys, etc., it will return the string that represents that key.
For example, pressing the “A” key will log "a" in the console, while pressing the Enter key will log "Enter". Keep in mind that the key values are case-sensitive.
In addition to event.key, you can also use event.keyCode, event.which, or event.code properties to get the key information. However, note that event.keyCode and event.which are deprecated and may not work consistently across all browsers, so it’s recommended to use event.key for modern event handling.
<a href="https://example.com" id="myLink">Click me</a>
const link = document.getElementById('myLink');

link.addEventListener('click', function(event) {
  event.preventDefault(); // Prevent the link from navigating to 'https://example.com'
  console.log('Link clicked, but default behavior prevented.');
});
2. event.stopPropagation(): The event.stopPropagation() method is used to stop the propagation of an event through the DOM tree. When an event occurs on an element, it is typically handled by that element first and then bubbles up through its ancestors, triggering event handlers along the way.
Calling event.stopPropagation() within an event listener prevents the event from further propagating up or down the DOM tree. This is useful when you don’t want an event to trigger event handlers on parent or descendant elements, potentially causing unintended side effects or conflicts.
Example:
<div id="outer">
  <button id="innerButton">Click me</button>
</div>
const outer = document.getElementById('outer');
const innerButton = document.getElementById('innerButton');

outer.addEventListener('click', function(event) {
  console.log('Clicked the outer div.');
});

innerButton.addEventListener('click', function(event) {
  event.stopPropagation(); // Prevent the click event from propagating to the outer div
  console.log('Clicked the inner button.');
});
If you click the button, you will see the output:
Clicked the inner button.

The event propagation is stopped by event.stopPropagation(), so the event handler on the outer div is not executed.

Combining event.preventDefault() and event.stopPropagation(): You can use event.preventDefault() and event.stopPropagation() together to both prevent the default behavior of an event and stop it from further propagating through the DOM tree.

const link = document.getElementById('myLink');

link.addEventListener('click', function(event) {
  event.preventDefault(); // Prevent the link from navigating to 'https://example.com'
  event.stopPropagation(); // Stop the event from propagating to parent elements
  console.log('Link clicked, but default behavior prevented, and propagation stopped.');
});
In summary, event.preventDefault() is used to prevent the default behavior of an event, while event.stopPropagation() is used to stop the event from propagating to ancestor or descendant elements. Understanding these methods allows you to have more control over event handling and create the desired behavior for your web applications.

      

Popular Category

Topics for You

HTML

Introduction
Html page 1
Html page 2
Html page3
Html page4

HTML Elements and structure
Html page 5
Html page 6
Html page 7

HTML Headings and Paragraphs
Html page 8
Html page 9
Html page 10

HTML Lists and Tables
Html page 11
Html page 12
Html page 13

HTML Forms and Input Fields
Html page 14
Html page 15
Html page 16

HTML Images and Media
Html page 17
Html page 18

HTML Links and Anchors
Html page 19
Html page 20
Html page 21

HTML Styles and Formatting
Html page 22

HTML Semantic Elements
Html page 23
Html page 24

HTML Attributes
Html page 25
Html page 26

HTML JavaScript Integration
Html page 27
Html page 28
Html page 29
Html page 30

HTML Document and Browser Support
Html page 31
Html page 32

HTML5 New Elements and Attributes
Html page 33
Html page 34
Html page 35
Html page 36

HTML Accessibility and Web Standards
Html page 37
Html page 38
Html page 39

HTML Responsive Design and Mobile Devices.
Html page 40
Html page 41
Html page 42

Go through our study material. Your Job is awaiting.

Recent Posts
Categories