xShub

Gestione eventi

Nov 7th, 2025 (edited)
264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Javascript
  2.  
  3.  
  4. let mioBottone = document.getElementById("mio-bottone");
  5. let mioDiv = document.getElementById("mio-div");
  6. let mioParagrafo = document.getElementById("mio-paragrafo");
  7.  
  8. mioParagrafo.addEventListener("click", gestioneEventi);
  9. mioBottone.addEventListener("click", gestioneEventi);
  10. // mioBottone.addEventListener("mouseover", eventoBottone);
  11. // mioBottone.addEventListener("mouseout", eventoBottone);
  12.  
  13. function stampaNelDiv(ilDiv, testoDaScrivereNelDiv) {
  14.     ilDiv.innerHTML = testoDaScrivereNelDiv;
  15. }
  16.  
  17. function gestioneEventi(mioEvento) {
  18.  
  19.     mioDiv.style.color = "";
  20.     let tipoEvento = mioEvento.type;
  21.     let elementoDellEvento = mioEvento.target;
  22.  
  23.     if (tipoEvento === "click") {
  24.         if (elementoDellEvento.id === "mio-paragrafo") {
  25.             // e' stato il paragrafo!
  26.             stampaNelDiv(mioDiv, "Hai cliccato sul paragrafo con id = " + elementoDellEvento.id)
  27.             // mioDiv.innerHTML = "Hai cliccato sul paragrafo con id = " + elementoDellEvento.id;
  28.         } else if (elementoDellEvento.id === "mio-bottone") {
  29.             // e' stato il bottone!
  30.             mioDiv.innerHTML = "Hai cliccato sul bottone con id = " + elementoDellEvento.id;
  31.         } else {
  32.             // non so chi sia stato! :-(
  33.             mioDiv.innerHTML = "Non so quale elemento abbia attivato l'evento click!";
  34.         }
  35.     } else if (tipoEvento === "mouseover" || tipoEvento === "mouseout") {
  36.         mioDiv.innerHTML = tipoEvento;
  37.     } else {
  38.         mioDiv.innerHTML = "Evento sconosciuto";
  39.         mioDiv.style.color = "red";
  40.     }
  41.  
  42.     // document.getElementById("mio-div").innerHTML = tipoEvento;
  43. }
  44.  
  45.  
  46. // HTML
  47.  
  48. <!DOCTYPE html>
  49. <html lang="en">
  50. <head>
  51.     <meta charset="UTF-8">
  52.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  53.     <title>Lezione 7 Novembre</title>
  54.     <script defer src="index.js"></script>
  55. </head>
  56. <style>
  57.  
  58.     body {
  59.         font-family: Arial, Helvetica, sans-serif;
  60.         font-size: 24px;
  61.     }
  62.  
  63. </style>
  64. <body>
  65.  
  66. <br>
  67. <br>
  68. <button id="mio-bottone">Start</button>
  69. <br>
  70. <p id="mio-paragrafo">Clicca qui</p>
  71. <br>
  72. <br>
  73. <div id="mio-div"></div>
  74. </body>
  75. </html>
Advertisement
Add Comment
Please, Sign In to add comment