Repository navigation
Events
J avaScript allows us to trigger work when it detects events. When JavaScript recognizes an event that applies to a "event handler" that has been set up, it will execute that "handler's" work, which is stored in a callback function.
addEventListener() allows us to associate "hearing" an event with executing a callback.
addEventListener(EventName, CallBackFunction) takes two arguments:
const input = document.getElementById('input');
input.addEventListener('click', function(event) {
alert('I was clicked!');
});document.addEventListener("keydown", function(e) {
console.log(e.key);
});press the left arrow key, we should see our console log ArrowLeft events. You can try it with other keys (Shift, Control, ArrowRight.
an important concept is that of the
event.target
element.addEventListener('click', function (event) {
event.target.innetText // shows the inner text of element
});We need to make sure to wait until after the DOMContentLoaded event is triggered to safely execute our code. By creating an event listener, we can keep our code from immediately firing when index.js is loaded.
document.addEventListener("DOMContentLoaded", function() {
console.log("The DOM has loaded");
});
console.log(
"This console.log() fires when index.js loads - before DOMContentLoaded is triggered"
);the DOMContentLoaded event fires once the initial HTML document finishes loading, but does not wait for CSS stylesheets or images to load. In situations where you need everything to completely load, use the load event instead.
HTML5 now has a defer attribute for use in <script> tags:
<script src="index.js" defer></script>This functions in a similar way to DOMContentLoaded - the JavaScript code stored in index.js will be loaded up but won't execute until the HTML page completely loads.
document.querySelector("#id-checkbox").addEventListener("click", function(event) {
document.getElementById("output-box").innerHTML += "Sorry! <code>preventDefault()</code> won't let you check this!<br>";
event.preventDefault();
}, false);