News:

Want to get involved in developing SMF? Why not lend a hand on our GitHub!

Main Menu

Javascript loading issue, where's the problem?

Started by Biology Forums, May 21, 2016, 01:33:19 PM

Previous topic - Next topic

Wellwisher

Quote from: nend on June 02, 2016, 01:27:07 AM
Sounds familiar.  ::)

I said you were partly right. :P Still, it feels like this script has a mind of its own. I feel spooked by it now. :laugh:

Biology Forums


leghorn23

Quote from: nend on June 02, 2016, 01:27:07 AM
Quote from: Wellwisher on June 02, 2016, 01:05:46 AM
In this unorthodox method, we can be sure the html element is loaded first, and the next item to load is the script itself. This rules out any conflicts and things should work:

Quote from: nend on May 21, 2016, 02:59:57 PM
Just put the JavaScript below the container and remove the onLoad function.

This //init clock
window.onload = function()
{
clock();
setInterval(\'clock()\', 1000);
}

To
//init clock
clock();
setInterval(\'clock()\', 1000);

Sounds familiar.  ::)

This could potentially introduce a race condition. Running code within a timeout should be a last resort IMO


leghorn23

You simply need to place the Javascript after the block that its adding the content to. This is because Javascript is referencing that div, so if it doesn't exist yet it will throw an error

Try this:


<span id="clock"></span>
<script type="text/javascript">
/*<![CDATA[*/
function clock()
{
// Generate time
var time = new Date();
var hours = time.getHours();
var minutes = time.getMinutes();
var seconds = time.getSeconds();

// Add preceding 0s, if required
var hours = (hours < 10 ? \'0\' : \'\')+hours;
var minutes = (minutes < 10 ? \'0\' : \'\')+minutes;
var seconds = (seconds < 10 ? \'0\' : \'\')+seconds;

// Generate formated time
var time = hours+\':\'+minutes+\':\'+seconds;

// Get where abouts in the day it is
if(hours >= 6 && hours < 12)
{
var greeting = \'Good morning\';
}
else if(hours >= 12 && hours < 18)
{
var greeting = \'Good afternoon\';
}
else if(hours >= 18 && hours < 21)
{
var greeting = \'Good evening\';
}
else
{
var greeting = \'Hello\';
}

// Display Greeting
document.getElementById(\'clock\').innerHTML = greeting;

//document.getElementById(\'clock\').innerHTML = time+\'<br />\'+greeting;
}

clock();
/*]]>*/
</script>

nend

Quote from: leghorn23 on August 19, 2016, 11:47:50 AM
You simply need to place the Javascript after the block that its adding the content to. This is because Javascript is referencing that div, so if it doesn't exist yet it will throw an error

Quote from: nend on May 21, 2016, 02:59:57 PM
Just put the JavaScript below the container and remove the onLoad function.

Advertisement: