Juri Juri - 1 month ago 8
HTML Question

Old javascript function for new html element

an existent (pure) javascript function doesn't work with a new html element (created after that function):



document.querySelector('li').onmouseover = function() {
document.querySelector("li").innerHTML ="Hai soffermato il mouse qui!";
}

document.querySelector('li').onmouseout = function() {
document.querySelector("li").innerHTML ="Sofferma il mouse qui";
}

document.getElementById('bottone1').onclick = function() {
var Lista = document.getElementById('lista');
var NuovoElemento = document.createElement('li');
NuovoElemento.innerText = 'Nuova voce'; // innerHTML
Lista.insertBefore(NuovoElemento, Lista.lastChild);
}

<p><b>Elenco puntato:</b></p>
<ol id="lista">
<li>Sofferma il mouse qui</li>
</ol>
<button id="bottone1">Aggiungi voce</button>





It's right so (but not good, imho), I know.
But, sorry, I don't understand this thread, that solves the problem (widthout explains it) :-(
Javascript function doesn't work when creating a new HTML element

Thanks (more solito).

Answer

You can solve this by applying the concept of event delegation. This means you listen to mouse events on the parent element instead of on the li elements. To make this possible, you need to consult the event object that is passed to the callback function, and check that the original element on which the mouse event originated, was indeed an li element:

document.getElementById('lista').onmouseover = function(e) {
  if (e.target.tagName !== 'LI') return false;
  e.target.textContent ="Hai soffermato il mouse qui!";
}

document.getElementById('lista').onmouseout = function(e) {
  if (e.target.tagName !== 'LI') return false;
  e.target.textContent ="Sofferma il mouse qui";
}

document.getElementById('bottone1').onclick = function() {
  var Lista = document.getElementById('lista');
  var NuovoElemento = document.createElement('li');
  NuovoElemento.textContent = 'Nuova voce';
  Lista.insertBefore(NuovoElemento, Lista.lastChild);
}
<p><b>Elenco puntato:</b></p>
<ol id="lista">
  <li>Sofferma il mouse qui</li>
</ol>
<button id="bottone1">Aggiungi voce</button>

Note that I also introduced the use of the textContent property which is to be favored above innerHTML when assigning plain text, to avoid side-effects that some strings otherwise could have (with < and & in them).