|
bookmarks:
|
| main | ongoing | archive | private |
<button>Change color</button>
const btn = document.querySelector("button");
function random(number) { return Math.floor(Math.random() * (number + 1)); }
btn.addEventListener("click", () => { const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`; document.body.style.backgroundColor = rndCol; });
the string "click", to indicate that we want to listen to the click event. Buttons can fire lots of other events, such as "mouseover" when the user moves their mouse over the button, or "keydown" when the user presses a key and the button is focused. a function to call when the event happens. In our case, the defined anonymous function generates a random RGB color and sets the background-color of the page <body> to that color.
const btn = document.querySelector("button");
function random(number) { return Math.floor(Math.random() * (number + 1)); }
function changeBackground() { const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`; document.body.style.backgroundColor = rndCol; }
btn.addEventListener("click", changeBackground);
There are many different events that can be fired by a button element. Let's experiment.
First, make a local copy of random-color-addeventlistener.html, and open it in your browser. It's just a copy of the simple random color example we've played with already. Now try changing click to the following different values in turn, and observing the results in the example:
focus and blur — The color changes when the button is focused and unfocused; try pressing the tab to focus on the button and press the tab again to focus away from the button. These are often used to display information about filling in form fields when they are focused, or to display an error message if a form field is filled with an incorrect value. dblclick — The color changes only when the button is double-clicked. mouseover and mouseout — The color changes when the mouse pointer hovers over the button, or when the pointer moves off the button, respectively.
Some events, such as click, are available on nearly any element. Others are more specific and only useful in certain situations: for example, the play event is only available on elements that have play functionality, such as <video>.
If you've added an event listener using addEventListener(), you can remove it again if desired. The most common way to do this is by using the removeEventListener() method. For example, the following line would remove the click event handler we saw previously:
btn.removeEventListener("click", changeBackground);
By making more than one call to addEventListener(), providing different handlers, you can have multiple handler functions running in response to a single event:
myElement.addEventListener("click", functionB);
We recommend that you use addEventListener() to register event handlers. It's the most powerful method and scales best with more complex programs. However, there are two other ways of registering event handlers that you might see: event handler properties and inline event handlers. Event handler properties
Objects (such as buttons) that can fire events also usually have properties whose name is on followed by the name of an event. For example, elements have a property onclick. This is called an event handler property. To listen for the event, you can assign the handler function to the property.
For example, we could rewrite the random color example like this:
function random(number) { return Math.floor(Math.random() * (number + 1)); }
btn.onclick = () => { const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`; document.body.style.backgroundColor = rndCol; };
function random(number) { return Math.floor(Math.random() * (number + 1)); }
function bgChange() { const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`; document.body.style.backgroundColor = rndCol; }
btn.onclick = bgChange;
element.onclick = function2;
You might also see a pattern like this in your code:
const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`; document.body.style.backgroundColor = rndCol; }
For a start, it is not a good idea to mix up your HTML and your JavaScript, as it becomes hard to read. Keeping your JavaScript separate is a good practice, and if it is in a separate file you can apply it to multiple HTML documents.
Even in a single file, inline event handlers are not a good idea. One button is OK, but what if you had 100 buttons? You'd have to add 100 attributes to the file; it would quickly turn into a maintenance nightmare. With JavaScript, you could easily add an event handler function to all the buttons on the page no matter how many there were, using something like this:
for (const button of buttons) { button.addEventListener("click", bgChange); }
You should never use the HTML event handler attributes — those are outdated, and using them is bad practice.
Sometimes, inside an event handler function, you'll see a parameter specified with a name such as event, evt, or e. This is called the event object, and it is automatically passed to event handlers to provide extra features and information. For example, let's rewrite our random color example to include an event object:
function random(number) { return Math.floor(Math.random() * (number + 1)); }
function bgChange(e) { const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`; e.target.style.backgroundColor = rndCol; console.log(e); }
btn.addEventListener("click", bgChange);
Most event objects have a standard set of properties and methods available on the event object; see the Event object reference for a full list.
Some event objects add extra properties that are relevant to that particular type of event. For example, the keydown event fires when the user presses a key. Its event object is a KeyboardEvent, which is a specialized Event object with a key property that tells you which key was pressed:
<div id="output"></div>
const output = document.querySelector("#output"); textBox.addEventListener("keydown", (event) => { output.textContent = `You pressed "${event.key}".`; });