Simply Java Script - Functions

Hello,

I am using a Sitepoint book “Simply Java Script by Kevin Yanks and Cameron Adams” to learn Java Script. I am on chapter 2 “functions” and I can’t get a snippet of code to work correctly. Here is what I am working with:

<html>
<head>
<title>The Running Man</title>
<meta http-equiv=“Content-Type”
content=“text/html; charset=utf-8”>

<script type=“text/javascript” src=“example.js”>
</script>

</head>
<body>
<p>Whatever you do, <em><a href=“#”>don’t click this
link</a></em>!</p>
</body>
</html>

My external script look like this:

function sandwich(bread, meat)
{
alert(bread + meat + bread);
}

I am expecting the alert box to pop up when my page load but it is not doing that. What am I doing wrong? The book is not clear on how to call the function.

I am expecting the alert box to pop up when my page load but it is not doing that. What am I doing wrong? The book is not clear on how to call the function.

The book is not clear because they forgot to move mention of page loading closer to the front of the book. But, they will mention it, later.

What they want you to do for now, before getting into window loaders (because there’s a pre-made one that deals with IE and all sorts of stuff in the back of the book that you will use later, a library called Core) is to put the script at the bottom of the page:


<p>Whatever you do, <em><a href="#">don't click this
link</a></em>!</p>
<script type="text/javascript" src="example.js">
</script>
</body>
</html>

That is, right before the closing body tag. What this does is make sure the link with the event has been loaded by the browser before the script goes looking for it.
This is why those Google trackers often sit at the bottom of web pages. They wait for the page to load.

Technically, the script only has to come after the element it’s supposed to Do Stuff to, but the bottom of the page is therefore always safe : )

Once you have a decent loading program with event listeners, you can choose whether you want to keep your scripts in the <head> or place them at the bottom of the body.

For a twist, you can also make the alert show when you click the “Dont click this link” :stuck_out_tongue:

<p>Whatever you do, <em><a href=“#” onclick=“sandwich(‘bread’, ‘meat’)”>don’t click this
link</a></em>!</p>

You just created the function but did not call it. If you want to run it when the pages is loaded then do something like this:


window.onload = sandwich('bread', 'meat');