Ir al contenido

02. Events

Events are actions that occur on the web page and can be detected by JavaScript. These events can be generated by:

0views

Events are actions that occur on a web page and can be detected by JavaScript. These events can be generated by:

  • The user: clicks, mouse movements, and key presses
  • The browser: full HTML load, completion of a CSS animation, browser window resizing, etc.

Frontend event management is fundamental because it allows us to:

  • Respond to user actions in real time.
  • Provide a practically immediate response.
  • Create a more dynamic and interactive UX (user experience).

JavaScript provides us with various methods to manage events. The modern and recommended method is addEventListener(), which allows us to:

  • Add multiple "listener functions" to the same element.
  • Generate entirely with JS. We keep the code separate from the HTML (better organization).
  • Offers different options (capturing an event, removing it, etc.).
EventDescription
clickWhen the user clicks with the mouse.
dblclickWhen the user double-clicks.
mousedownWhen the user presses the mouse button.
mouseupWhen the user releases the mouse button.
mouseoverWhen the mouse hovers over an element.
mouseoutWhen the mouse leaves the element.
keydownWhen the user presses a key.
keyupWhen the user releases a key.
submitWhen a form is submitted.
loadWhen the page or a resource has fully loaded.
resizeWhen the window is resized.

We will capture the mouse click on a button.

<button id="boton-inicio">A jugar!</button>
const boto = document.querySelector("#boton-inicio");
boto.addEventListener('click', () => {
alert('¡El jugador ha iniciado el juego!');
});

Mouse Event Example with Event Management (click with event)

Sección titulada «Ejemplo de Evento de Ratón con Gestión de Evento (click con event)»

We will capture the mouse click on the screen and manage the event.

<div id="pantalla-juego"></div>
#pantalla-juego {
background-color: lightblue;
width: 100vw;
height: 100vh;
}
const pantalla = document.querySelector('#pantalla-juego');
pantalla.addEventListener('click', (eventRatoli) => {
console.log(`Clic en la posición: ${eventRatoli.clientX}, ${eventRatoli.clientY}`);
console.log(eventRatoli); //Podemos ver el contenido del evento
});

We will capture the key pressed by the user and manage the event.

const teclasCounter = {
ArrowUp: 0,
ArrowDown: 0,
Space: 0
}
document.addEventListener('keydown', (eventTeclado) => {
switch(eventTeclado.code) {
case 'ArrowUp': // Mover al jugador hacia arriba
teclasCounter.ArrowUp++;
console.log("Tecla arriba (ArrowUp) presionada.");
break;
case 'ArrowDown': // Mover al jugador hacia abajo
teclasCounter.ArrowDown++;
console.log("Tecla abajo (ArrowDown) presionada.");
break;
case 'Space': // Disparar o atacar
teclasCounter.Space++;
console.log("Tecla espacio (Space) presionada.");
break;
}
});