Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created January 31, 2019 18:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/3a0200a72726ab4ed472c89cf6439a61 to your computer and use it in GitHub Desktop.
Save parzibyte/3a0200a72726ab4ed472c89cf6439a61 to your computer and use it in GitHub Desktop.
Escuchar click de botones created by parzibyte - https://repl.it/@parzibyte/Escuchar-click-de-botones
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Escuchar click de botones</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<button class="botones">Soy un botón</button>
<br><br>
<button class="botones">Otro botón</button>
<br><br>
<button class="botones">Botón 3</button>
<br><br>
<button class="botones">Botón 4</button>
<br><br>
<button class="botones">Botón 5</button>
<br><br>
<button class="botones">Último botón</button>
<br><br>
<script src="script.js"></script>
</body>
</html>
// Obtener referencia a botones
// Recuerda: el punto . indica clases
const botones = document.querySelectorAll(".botones");
// Definir función y evitar definirla de manera anónima
const cuandoSeHaceClick = function (evento) {
// Recuerda, this es el elemento
console.log("El texto que tiene es: ", this.innerText);
// Podemos cambiar cualquier cosa, p.ej. el estilo
this.style.borderColor = "blue";
}
// botones es un arreglo así que lo recorremos
botones.forEach(boton => {
//Agregar listener
boton.addEventListener("click", cuandoSeHaceClick);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment