I was trying to write this basic JavaScript program which changes the background color when a button is pressed.
When I place this JS code inside the ‘head’ tags it does NOT work but when I place it inside the ‘body’ tag it does. (When placing inside body I removed window.onload)
<script>
window.onload = function(){
var para = document.getElementById("para");
function togglecolor(){
if(para.className != "yellow") para.className = "yellow";
else para.className = "notYellow";
}
}
</script>
Here’s the HTML:
<h1 id="para" class="">Hello World! </h1>
<button onClick="togglecolor();">Press Me</button>
I am unable to understand why it does not work when places inside ‘head’.
It’s a scope issue. You are defining your function within another function. This means it is only accessible inside that function. Move it outside and everything should work.