Nathan J
Nathan J

Reputation: 193

Uncaught ReferenceError: clickWorld is not defined -- Function not defined?

Ok, so i have been coding in javascript for about 3 hours and i'm allready stuck. It looks so simple, but, whenever i run and click on "Hello" i get an error saying "Uncaught ReferenceError: clickWorld is not defined". I did some google searches and found a few tricks i.e. windows.onload and placing the script tag directly before /body. Neither solved by problem. I'm now seeking additional help. Here is my code...

<!DOCTYPE html>
<html>
<head> 
</head>

<div id="javatest" onclick="clickWorld()">Hello</div>
<body>
<script type="text/javascript">
window.onload = function() {
function clickWorld()
    {
    alert("BANG");
    }
}
</script>
</body>
</html>

I really appreciate the help as i can't move on in my learning until this is solved. Thanks so much!

Upvotes: 0

Views: 1494

Answers (2)

Satpal
Satpal

Reputation: 133433

Instead of

window.onload = function () {
    function clickWorld() {
        alert("BANG");
    }
}

Use

function clickWorld() {
    alert("BANG");
}

Additionaly

Put your div in body, currently your div is in head section

DEMO

Upvotes: 0

Polynomial
Polynomial

Reputation: 3706

It looks like you're trying to use an anonymous function with window.onload, which should correctly be written like this:

window.onload = function() {
    alert("BANG");
};

By putting it inside the window.onload like that you make it so it's out of scope - essentially your div can't 'see' the javascript. For your purposes, you probably don't want the window.onload there at all - it's unnecessary. All you need inside your script tag is:

function clickWorld() {
    alert("BANG");
}

You also need to move your div from between the head and body tags - it should be inside the body tag.

If you want multiple functions inside your script tag, just add them like this:

function someFunc1() {
    // Do stuff
}

function someFunc2() {
    // Do stuff
}

Upvotes: 1

Related Questions