javascript – Alternative: separate JS from HTML


My project consists of an html and a js file that simulate the operation of an analog clock. It works correctly but I would like not to have to mention the js function from the html () as I have it and look for an alternative referring from a script for example only and add a call or a method in the js file that launches the function


<body onload="funcionReloj()">

   <div id="cajacontenido">
        <div id="aplicacion">
            <div id="CajaReloj">
                <img id="segundos" src="./IMG/Aguja3.png" alt="Manilla segundos reloj" />
                <img id="minutos" src="./IMG/Aguja2.png" alt="Manilla pequeña reloj" />
                <img id="hora" src="./IMG/Aguja1.png" alt="Manilla grande reloj" />

And as for my js file:

function funcionReloj() {
    var momentoActual = new Date();//Crea hora
    var horaActual = momentoActual.getHours();//Extraemos Hora
    var minutoActual = momentoActual.getMinutes();//Extraemos Minutos
    var segundoActual = momentoActual.getSeconds();//Extraemos Segundos

    //Identificadores para elementos
    var hora = document.getElementById('hora');
    var minutos = document.getElementById('minutos');
    var segundos = document.getElementById('segundos');

    function cambiarHora() {
        //Calcular grados por hora (30deg cada hora, 30*12=360º)
         var horaActualGrados = horaActual * 30 + "deg"; = "rotate(" + horaActualGrados + ")";

        //Calcular grados cada minuto (6deg cada minuto, 6*6=360º)
         var minutoActualGrados = minutoActual * 6 + "deg"; = "rotate(" + minutoActualGrados + ")";

    function cambiarSegundos() {
        //Calcular grados cada segundo (6deg cada segundo, 6*6=360º)
        var segundoActualGrados = segundoActual * 6 + "deg"; = "rotate(" + segundoActualGrados + ")";


    //Actualizar reloj

    //Actualizar reloj cada segundo
    //    setTimeout("cambiarSegundos()",1000);



Instead of putting the onLoad in the tag, you can put it in your .js file as a window event. When the window loads, launch your function. Something like this:

 function tuFuncion() { // .... console.log("Se ejecutó al cargar"); } window.addEventListener("load", tuFuncion);

With addEventListener associate the type of event that you want to trigger the execution of the function (here you can see a list of the types of events ). In the above code you are saying that when the window ( window ) is loaded ( load ) a function ( tuFuncion ) is called.

In your case it would be like this:

window.addEventListener("load", funcionReloj);
Scroll to Top