|
11 | 11 | | [Understanding 'Capturing' & 'Bubbling' Phases](#understanding-capturing--bubbling-phases) | |
12 | 12 | | [Event Propagation and `stopPropagation()`](#event-propagation-and-stoppropagation) | |
13 | 13 | | [Using Event Delegation](#using-event-delegation) | |
| 14 | +| [Triggering DOM Elements Programmatically](#triggering-dom-elements-programmatically) | |
14 | 15 |
|
15 | 16 | ## [Introduction to Events in JavaScript](https://drive.google.com/uc?export=view&id=1tfi-wZ9BYL2wISnyZ2JCcutRPApHpyCV) |
16 | 17 |
|
@@ -633,3 +634,35 @@ Readings: |
633 | 634 | - [Event Delegation in JavaScript](https://www.freecodecamp.org/news/event-delegation-javascript/) |
634 | 635 |
|
635 | 636 | - [JavaScript Event Delegation: A Beginner's Guide](https://dmitripavlutin.com/javascript-event-delegation/) |
| 637 | +
|
| 638 | +## Triggering DOM Elements Programmatically |
| 639 | +
|
| 640 | +There may be situations where you not only need to listen to an event, but also trigger an event programmatically. An example will be demonstrated of such scenario in later modules. For now, let's take a glimpse of how this can be done. |
| 641 | +
|
| 642 | +Let's say from an event, there is a need to trigger another event. For example, |
| 643 | +
|
| 644 | +```HTML |
| 645 | +<!DOCTYPE html> |
| 646 | +<html> |
| 647 | +<head> |
| 648 | + <title>Triggering DOM Events Programatically</title> |
| 649 | +</head> |
| 650 | +<body> |
| 651 | + <button id="know-me">Click to know me!</button> |
| 652 | + <button id="trigger">I click another buttons</button> |
| 653 | + <script> |
| 654 | + const knowMeBtn = document.getElementById('know-me'); |
| 655 | + const triggerBtn = document.getElementById('trigger'); |
| 656 | + knowMeBtn.addEventListener('click', () => { |
| 657 | + console.log("Hello! My name is Foo and I work at bar ;D"); |
| 658 | + }); |
| 659 | + triggerBtn.addEventListener('click', () => { |
| 660 | + console.log('Hehehehe! I click other buttons...'); |
| 661 | + knowMeBtn.click(); |
| 662 | + }); |
| 663 | + </script> |
| 664 | +</body> |
| 665 | +</html> |
| 666 | +``` |
| 667 | +
|
| 668 | +It has two buttons - "Click to know me!" and "I click other buttons" - and a script that adds an event listener to each button. When the "Click to know me!" button is clicked, it logs a message to the console. When the "I click other buttons" button is clicked, it logs a different message to the console and then programmatically triggers a click event on the "Click to know me!" button using the [`click()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click) method. Overall, the code works as expected. |
0 commit comments