Hello JavaScript

We are about to write a few JavaScript lines, just to see the point of using this language.

We'll how to write a JavaScript function, and how to call JavaScript function reacting to events happening on our HTML page.

To do that, we create a simple page displaying an image, spicing it up adding a few requisites:
  • we want to cheer the user with a popup message anytime the page is loaded (quite unnerving, in the long run);
  • anytime he clicks on the picture we ask him his name, so to politely say again hello to him personally, besides, we change picture and its alternate text.
Here is the page, below a few notes on it:

<html>
<head>
<title>A friendly page</title>
<script type="text/javascript">
function feedBack() {
var name = prompt("What's your name?", "Enter your name here");
if(name) {
alert("Nice meeting you, " + name + "!");
document.getElementById("img").src = "image2.png";
document.getElementById("img").alt = "another image";
}
}
</script>
</head>
<body onload="alert('Hello from a friendly page!')">
<img id="img" src="image1.png" alt="an image" style="cursor:pointer"
onclick="feedBack()" />
</body>
</html>

The script tag is used to include the code in an HTML page. Its type attribute specify the language - text/javascript in our case. Typically, we put the script section in the HTML tag - just a convention.

The function keyword marks a JavaScript function, and var is used for identifying a variable.

The standard prompt() function popups a window with the passed title and label for the input line showed to the user. The text entered is returned to the caller, if no text is entered, a null is returned.

The standard alert() function popups a window with the specified message in it.

We can access elements in the HTML page in a number of way. Here we see how to call the function getElementById() on the document to get the element with the specified id. Once we have the element, we can access its properties.

The onload event handler, used in the body tag, let us react to the complete loading of the page.

We specifiy the id of the image, so that we have a easy way to retrieve it from our custom JavaScript function.

The attribute style here is used to make the cursor shape change when we hover over it.

The onclick event handler, specified for an element in the body, let us a way to react to the user click on it.

To refresh my JavaScript I'm reading Head First JavaScript, a fun book I suggest you, if you want to do the same. I wrote this post as a comprehension exercise on its chapter one.

No comments:

Post a Comment