JavaScript

Event Attachment

by Andrea Spera

Esempio di utilizzo del metodo addEventListener
addEventListener è un metodo JavaScript che consente di associare una funzione a un evento specifico di un elemento HTML, come il clic di un bottone o il caricamento della pagina. A differenza di altre tecniche, permette di aggiungere più gestori di eventi allo stesso elemento senza sovrascrivere i precedenti, garantendo maggiore flessibilità.
Codice
<!DOCTYPE html>
<html>
<head>
<script>
function clickFunct()
	{
	let a;
	a = document.getElementById("counterId").innerHTML;
	document.getElementById("counterId").innerHTML = parseInt(a, 10 ) + 1;
	}
function mouseOverFunct()
	{
	document.getElementById("divId").style.color="white";
	}
function mouseOutFunct()
	{
	document.getElementById("divId").style.color="inherit";
	}
</script>
</head>
<body>
<div id="divId" style="cursor:pointer;">Click here</div>
<script>
document.getElementById("divId").addEventListener("click", clickFunct);
document.getElementById("divId").addEventListener("mouseover", mouseOverFunct);
document.getElementById("divId").addEventListener("mouseout", mouseOutFunct);
</script>
</body>
</html>
Output
Click here
0
Passare variabili ad una funzione richiamata da addEventListener
Codice
<!DOCTYPE html>
<head>
<script>
function functWithVar(inputId)
	{
	let tmp;
	tmp = document.getElementById(inputId).innerHTML;
	document.getElementById("outputId").innerHTML = "You have clicked the " + tmp;
	}
</script>
</head>
<body>
Click one of the following:
<ul>
	<li id="aId" style="cursor:pointer;">A</li>
	<li id="bId" style="cursor:pointer;">B</li>
	<li id="cId" style="cursor:pointer;">C</li>
</ul>
<div id="outputId">...</div>
<script>
document.getElementById("aId").addEventListener("click", function(){
	functWithVar(this.id);});
document.getElementById("bId").addEventListener("click", function(){
	functWithVar(this.id);});
document.getElementById("cId").addEventListener("click", function(){
	functWithVar(this.id);});
</script>
</body>
</html>
Output
Click one of the following:
  • A
  • B
  • C
...