Javascript Code works in jsfiddle and but not in the Browser [closed]

The usual reason for this is that you’re putting your code above the elements that it operates on, and not delaying the code using onload or “ready” events. jsFiddle’s default is to put your JavaScript in an onload handler, which delays it until very late in the page load process.

Fundamentally, before your code can do something with an element on the page, the element has to exist. For it to exist, the browser must have processed the HTML for it. So this fails:

<html>
<head>
<script>
// FAILS
document.getElementById("foo").style.color = "green";
</script>
</head>
<body>
<div id="foo">This is foo</div>
</body>
</html>

but this works:

<html>
<head>
</head>
<body>
<div id="foo">This is foo</div>
<script>
// Works
document.getElementById("foo").style.color = "green";
</script>
</body>
</html>

Do I need an onpage load event?

Almost certainly not.

Does the javascript need to be put in a function?

Not necessarily. What you do is put the script tag at the very end of the HTML, just before the closing </body> tag.

Leave a Comment