0

Somebody knows what is wrong in "addEventListener"?

var arr = document.getElementById("fecha"); arr. addEventListener("click",horaActual,false);

26th Jan 2017, 2:43 PM
Emmanuel Moreno
Emmanuel Moreno - avatar
5 odpowiedzi
+ 2
Your script is in the <head>, so it is loaded before html <body> content, and when you attempt to get the element by id, the element doesn't yet exist, so your 'arr' variable contains 'null'... You can fix it by at least two way: - embed your code ( at least the two lines initializing the event listener ) in a function attributed to the window.onload event - inline the 'fecha' onclick event in the tag ( <p id="fetcha" onclick="horaActual();"> )
27th Jan 2017, 5:10 AM
visph
visph - avatar
0
You have the object (function) horaActual implemented, can't see anything else based on the posted code.
26th Jan 2017, 3:54 PM
Jani Sinkkonen
Jani Sinkkonen - avatar
0
Yes, there is a function called horaActual, the error is in that instruction "addEventListener"
26th Jan 2017, 6:16 PM
Emmanuel Moreno
Emmanuel Moreno - avatar
0
<!DOCTYPE html> <html> <head> <title>Fecha y saludo</title> <script type="text/javascript"> function horaActual() { var fecha = new Date(); var hora = fecha.getHours(); var minutos = fecha.getMinutes(); var seg = fecha.getSeconds(); alert(hora + ":" + minutos + ":" + seg); } var arr = document.getElementById("fecha"); arr. addEventListener("click",horaActual,false); </script> </head> <body> <p id="fecha">Click para fecha actual</p> <p>click para saludo</p> </body> </html>
26th Jan 2017, 6:18 PM
Emmanuel Moreno
Emmanuel Moreno - avatar
0
Thanks for your help, it works perfectly
27th Jan 2017, 3:33 PM
Emmanuel Moreno
Emmanuel Moreno - avatar