bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/JavaScript/DOM and Browser APIs
JavaScript•DOM and Browser APIs

JavaScript Event Management

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind JavaScript Event Management?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

<button id="btn">Click</button> <p id="demo"></p> <script> ___ btn = document.getElementById("btn");
3Order

Put the learning moves in the order that makes the concept easiest to apply.

To remove an event listener, you must use the same named function you used to add it.
Event Management is about adding, removing, and controlling events.
JavaScript Event Management

Event Management is about adding, removing, and controlling events.

Adding Events

Example

<button id="btn">Click</button> <p id="demo"></p> <script> const btn = document.getElementById("btn");
// Let btn listen for click btn.addEventListener("click", myFunction); function myFunction() { document.getElementById("demo").innerHTML = "Clicked!";
}
</script>

Removing Events

Example

<button id="add">Add</button> <button id="remove">Remove</button> <button id="test">Test click</button> <p id="demo"></p> <script> const test = document.getElementById("test");
const remove = document.getElementById("remove");
const add = document.getElementById("add");
function myFunction() {
  document.getElementById("demo").innerHTML += "Hello!";
}
// Let add listen for click add.addEventListener("click", function () { // Let test listen for click test.addEventListener("click", myFunction);
});
// Let remove listen for click remove.addEventListener("click", function () { // Prevent test from listen for click test.removeEventListener("click", myFunction);
});
</script>

To remove an event listener, you must use the same named function you used to add it.

Blocking Events

Example

<a href="https://example.com id="link">Go to ExampleSite</a> <p id="demo"></p> <script> const link = document.getElementById("link"); // Let link listen for click link.addEventListener("click", function (event) { event.preventDefault(); document.getElementById("demo").innerHTML = "Link blocked!"; }); </script>

Previous

JavaScript Timing Events

Next

JavaScript HTML DOM Events