Reputation: 3393
I have just started working through Professional JavaScript for Web Developers and am trying to run the code as I go along. I have hit a wall early on with trying to embed JavaScript in a HTML document. If I define a function and call it in the same document, nothng happens. Similarly, if I define a function in the document and call it from either the Firefox scratchpad or FireBug nothing happens. I can however run the whole thing (define the function and call it) from the scratch pad or FireBug.
The code I am using for the page is:
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
<script type="text/javascrtipt">
function compare(a, b) {
if (a < b) {
alert ("A is less than B");
} else if (a > b) {
alert ("A is greater than B");
} else {
alert ("A is equal to B");
}
};
</script>
</head>
<body>
<p>Paragraph 1</p>
<script type="text/javascript">compare(5, 6);</script>
</body>
</html>
I have found similar questions like the one below which I think answers my question but I don't understand it enough to apply it to my scenario. How would I make the function above global (if that is whats needed here)?
Calling custom functions from firebug console
Thanks,
Ger
Upvotes: 0
Views: 293
Reputation: 11
The problem here is not in your logic, rather it is in a simple typing error. Where you specify the script type in the head, you misspelled javascript - correct that and the script executes.
Further to this, it may be worth mentioning that, when using the HTML5 doctype, you omit the script type if you wish because this is now the default for HTML5 documents.
Upvotes: 1
Reputation: 2423
After correcting the typo "text/javascrtipt" the compare function can be successfully called from Firebug console (command editor) with, e.g.
compare(3,4);
and a following click on "execute". Tested with Firefox 24.0 / Linux.
Upvotes: 0