Javascript Event How to - Create mouse rollover handler on dynamically created html element








Question

We would like to know how to create mouse rollover handler on dynamically created html element.

Answer


<!DOCTYPE html>
<html>
<body>
  <div id="channels_buttons_container"></div>
<script type='text/javascript'>
<!--  ww  w  .ja v  a2s. c o  m-->
channels_array = ["red", "green", "black"];
for(var i = 0; i < channels_array.length; i++) {
    loop_channel_name = channels_array[i];

    var new_button_element = document.createElement("span");
    new_button_element.id = 'channel_button_'+loop_channel_name;
    new_button_element.innerHTML = '<br>test';
    document.getElementById('channels_buttons_container').appendChild(new_button_element);

    document.getElementById('channel_button_'+loop_channel_name).onmouseover = function(){
        document.writeln('Rollover '+this.id);
    }
}

</script>
</body>
</html>

The code above is rendered as follows: