How not to use onload on the body with this code?

Asked

Viewed 94 times

-2

I would like to know how to use the following code:

function startTime() {
    var dateString = new Date().toLocaleString("en-US", {timeZone: "America/Sao_Paulo"});
    $('#txt').attr("data-original-title", dateString, 1000);
    setTimeout(startTime, 1000);
}

Without having to add that to your body:

<body onload="startTime();">

2 answers

0


You can invoke the function startTime when the page is loaded.

<script>
  function startTime() {
    let dateString = new Date().toLocaleString("en-US", {timeZone: "America/Sao_Paulo"});
$('#txt').attr("data-original-title", dateString, 1000);
setTimeout(startTime, 1000);
  }

  window.addEventListener('load', startTime)
</script>
  • Thank you so much for your help!

0

You can use the property window onload. which performs a function as soon as all page content is loaded, getting as follows:

<script>
  function startTime() {
    let dateString = new Date().toLocaleString("en-US", {timeZone: "America/Sao_Paulo"});
    $('#txt').attr("data-original-title", dateString, 1000);
    setTimeout(startTime, 1000);
  }

   window.onload = startTime;
</script>
  • Thank you so much for your help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.