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

const button = document.getElementById('myButton');

button.addEventListener('click', function() {
  // Code to be executed when the button is clicked
});
3. Handle the Event: In the event listener function, you can write the code that should be executed when the event occurs. For example, if you want to display an alert when a button is clicked:
const button = document.getElementById('myButton');

button.addEventListener('click', function() {
  alert('Button clicked!');
});
You can add event listeners to various elements on the page, and you can also remove event listeners if needed using the removeEventListener method.
Events in JavaScript are essential for building dynamic and interactive web applications. They allow developers to respond to user actions and create engaging user experiences.
const button = document.getElementById('myButton');

button.addEventListener('click', function() {
  // Code to be executed when the button is clicked
});
3.  Define the Event Handler Function: Inside the event listener function, you can write the code that should be executed when the event occurs. This is the code that handles the event.
const button = document.getElementById('myButton');

function handleClick() {
  // Code to be executed when the button is clicked
}

button.addEventListener('click', handleClick);
4. Remove the Event Listener (Optional): If you want to remove the event listener at some point, you can use the removeEventListener method. This can be helpful if you dynamically add and remove event listeners during the application’s lifecycle to avoid memory leaks.
const button = document.getElementById('myButton');

function handleClick() {
  // Code to be executed when the button is clicked
}

button.addEventListener('click', handleClick);

// Later, if you want to remove the event listener:
button.removeEventListener('click', handleClick);
By following these steps, you can handle events in JavaScript and create interactive web applications that respond to user actions in a dynamic and engaging manner.
<section>
  <div>
    <button>Click me</button>
  </div>
</section>
If you click the button, the event will first trigger the button’s event handler, and then the event will bubble up to the div element, then to the section, and finally to the document object. If any of these elements have event listeners for the same event, those listeners will be executed in sequence.
Event Capturing: Event capturing is less commonly used than event bubbling but can be explicitly enabled for certain elements. In the event capturing phase, the event is first captured at the root element (document), and then it travels down the DOM tree until it reaches the innermost element that triggered the event.
To enable event capturing, you can use the addEventListener method with a third parameter set to true.
const button = document.getElementById('myButton');

button.addEventListener('click', function() {
  // Event capturing phase (will be executed first)
}, true);
In the example above, when the button is clicked, the event will first trigger the event listener during the capturing phase, and then it will propagate back up the DOM tree during the bubbling phase.
Summary: In summary, event bubbling starts from the innermost element and moves up the DOM tree, while event capturing starts from the root element and moves down the DOM tree. Event bubbling is the default behavior in modern browsers, and it’s generally easier to work with. Event capturing is less common but can be useful in specific scenarios where you want to handle events at the top of the DOM hierarchy first.
const button = document.getElementById('myButton');

button.addEventListener('click', function() {
  console.log('Event listener 1');
});

button.addEventListener('click', function() {
  console.log('Event listener 2');
});
In this example, clicking the button will trigger both event listeners, and you will see both messages in the console.
On the other hand, with onclick, if you assign a new value to it, the previously attached handler will be overwritten:
const button = document.getElementById('myButton');

button.onclick = function() {
  console.log('Event handler 1');
};

// This will replace the previous onclick handler
button.onclick = function() {
  console.log('Event handler 2');
};
In this case, only the second event handler will be executed when you click the button.
2. Event Binding Time: Another important difference is the time when the event handlers are bound to the element. With addEventListener, you can attach event listeners at any time, even after the initial page load. This makes it more flexible and allows you to dynamically add and remove event handlers as needed.
const button = document.getElementById('myButton');

button.addEventListener('click', function() {
  console.log('Button clicked!');
});
In contrast, onclick is typically used as an inline event handler directly within the HTML element. This means the event handler is bound to the element at the time the page is loaded, and it cannot be easily changed or removed later in the code. Inline event handlers also have some drawbacks, as they mix JavaScript code with HTML markup, which can make the code less maintainable.
<!-- Inline event handler -->
<button id="myButton">Click me</button>
Conclusion: In general, it is recommended to use addEventListener for attaching event handlers because of its flexibility to handle multiple handlers, dynamic binding, and better separation of JavaScript and HTML code. It is considered a more modern and robust approach for handling events in JavaScript. On the other hand, onclick can be useful for simple scenarios where you only need a single event handler and want a quick way to set it up directly in the HTML markup.
const link = document.getElementById('myLink');

link.addEventListener('click', function(event) {
  event.preventDefault(); // Prevent the default behavior of clicking a link
  // Your custom code here...
});
In this example, when the link is clicked, the event listener function will be executed. Inside the function, event.preventDefault() is called, which prevents the default action of following the link. This allows you to handle the click event with your custom code instead.
Similarly, you can use preventDefault() for other events as well, such as form submissions or key presses:
const form = document.getElementById('myForm');

form.addEventListener('submit', function(event) {
  event.preventDefault(); // Prevent the default form submission
  // Your custom code here...
});
const inputField = document.getElementById('myInput');

inputField.addEventListener('keydown', function(event) {
  if (event.key === 'Enter') {
    event.preventDefault(); // Prevent the default "Enter" key behavior in the input field
    // Your custom code here...
  }
});
By preventing the default behavior of events when necessary, you can have more control over how your web application responds to user interactions and create a better user experience.
<div id="outer">
  <button id="innerButton">Click me</button>
</div>


  const outerDiv = document.getElementById('outer');
  const innerButton = document.getElementById('innerButton');

  outerDiv.addEventListener('click', function(event) {
    console.log(event.target); // Output: <button id="innerButton">Click me</button>
  });

  innerButton.addEventListener('click', function(event) {
    console.log(event.target); // Output: <button id="innerButton">Click me</button>
  });

2. event.currentTarget:
  • event.currentTarget refers to the element that the event handler is attached to. It represents the element that is currently handling the event as it bubbles up through the DOM tree.
  • During the capturing and bubbling phases of the event propagation, event.currentTarget remains the same (the element with the attached event listener) regardless of where the event originated (event.target).
Example:
<div id="outer">
  <button id="innerButton">Click me</button>
</div>


  const outerDiv = document.getElementById('outer');
  const innerButton = document.getElementById('innerButton');

  outerDiv.addEventListener('click', function(event) {
    console.log(event.currentTarget); // Output: <div id="outer">...</div>
  });

  innerButton.addEventListener('click', function(event) {
    console.log(event.currentTarget); // Output: <div id="outer">...</div>
  });

In summary, event.target always represents the element that triggered the event, while event.currentTarget always represents the element with the attached event listener, regardless of where the event was originally triggered. Understanding these differences is essential for handling events in complex DOM structures and for making decisions based on which element the event was triggered on versus which element is currently handling the event.

      

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