Olof
Olof

Reputation: 797

onload doesn't work while onmouseenter does

I have done a simple JS function and tried to call it with onload="updateClock()" but without any success. But if i change to onmouseenter="updateClock()" it works perfectly then I hover over with the mouse.

Why doesn't it work?

HTML:

<script src="clock.js" type="text/javascript"></script>
<section onload="updateClock();">
    <span id="clock">00:00:00</span>
</section>

JS:

function updateClock(){

    var currentTime = new Date ();

    var hours = currentTime.getHours ();
    var minuts = currentTime.getMinutes ();
    var seconds = currentTime.getSeconds ();

    //Pad with zeros
    hours = (hours < 10 ? "0" : "") + hours;
    minuts = (minuts < 10 ? "0" : "") + minuts;
    seconds = (seconds <10 ? "0" : "") + seconds;

    var time = hours + ":" + minuts + ":" + seconds;

    document.getElementById("clock").innerHTML = time;
}

Upvotes: 2

Views: 89

Answers (1)

Teemu
Teemu

Reputation: 23406

Only elements like iframe or img, in general, elements which can have content loaded from an external resource, have onload event. (And some DOM objects, like window ofcourse.)

A quick-fix would be to move the script tag after the section and use an IIFE:

<section>
    <span id="clock">00:00:00</span>
</section>
<script src="clock.js" type="text/javascript"></script>

And in clock.js:

(function updateClock(){
         :
}());

Upvotes: 2

Related Questions