Dave Dave - 5 months ago 7
HTML Question

javaScript is not recognised at all

I have created a simple web page so I can use JavaScript. The code below is a very small piece of it. The javascript I have wrote in it will not do anything. I don't know why. I know this isn't something difficult to do but I have no idea what is wrong with it. Its like the script isn't recognized by the browser at all. Could someone please help me with this problem?

<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8" />
<title>Add User</title>
<link rel="shortcut icon" href="logo.png"/>
<link rel="stylesheet" href="style.css" type="text/css"/>
<script type="text/javascript">
function changeBackground()
{
alert("Java is working!");
document.getElementByID("top_nav").background-color = "green";
document.getElementByID("top_nav").innerHTML = "green";
}
</script>
</head>
<body>
<div id="top_nav" onload="changeBackground()" style="height: 500px; width: 500px;">
<button type="button" onclick="changeBackground()">button</button>
</div>
</body>
</html>

Answer

There is no div 'onload' event. You weren't calling the correct function (javascript is case sensitive) for getting the element by ID, it's backgroundColor not background-color, and it's off the style object, not the html element itself.

Also, this is JavaScript.

<!DOCTYPE HTML>
    <html>
        <head>
            <meta charset="UTF-8" />
            <title>Add User</title>
            <link rel="shortcut icon" href="logo.png"/>
            <link rel="stylesheet" href="style.css" type="text/css"/>
            <script type="text/javascript">     
                function changeBackground() 
                {
                    alert("JavaScript is working!");
                    document.getElementById("top_nav").style.backgroundColor = "green";
                    document.getElementById("top_nav").innerHTML = "green";
                }
            </script>
        </head>
        <body>
        <div id="top_nav" style="height: 500px; width: 500px;">
<button type="button" onclick="changeBackground()">button</button>
</div>
        </body>
        </html>
Comments