Pages

Persistence by cookies

We can't access the secondary store on the local machine with JavaScript, with the exception of cookies. So, we use a cookie to store basic information for a page.

A cookie is identified by a unique name, it is used to store a value, and it has an expiration date. All the cookies are stored in a string associated to the current web page, that makes them a bit wierd to manage. So it is customary to write a tiny library of JavaScript functions to keep easy the user code.

Here is how we are going to save a cookie:

function writeCookie(name, value, secs) {
// by default the cookie is temporary
var expires = "";

// cookie persistent for the passed number of seconds
if(secs) {
var date = new Date();
date.setTime(date.getTime() + secs * 1000);
expires = "; expires=" + date.toGMTString();
}

// set the cookie to the name, value, and expiration date
document.cookie = name + "=" + value + expires + "; path=/";
}

Normally, it would be more useful if the third parameter of writeCookie() was the number of days. But for testing purposes it is handy having a cookie that expires in a few seconds.

Once a cookie is stored, we should retrieve it:

function readCookie(name) {
var searchName = name + "=";
var cookies = document.cookie.split(';');
for(var i=0; i < cookies.length; i++) {
var c = cookies[i];
while (c.charAt(0) == ' ')
c = c.substring(1, c.length);
if (c.indexOf(searchName) == 0)
return c.substring(searchName.length, c.length);
}
return null;
}

As we said, the code is a bit involute. We split document.cookie in an array of cookies, using semicolon (";") as delimiter. [This is cool, but it leads to the inconvenience that we can't store semicolon in our cookie!]
Then we loop on all the cookies, we skip all the trailing blanks, and check for the key, if we find it then we return the substring starting just after the equal sign to the end of the current cookie.

To erase a cookie we just change it assigning a negative value as expiration:

function eraseCookie(name) {
writeCookie(name, "", -1);
}


More on JavaScript cookies in chapter three of Head First JavaScript.

Go to the full post

Size matters

We have showed a picture to the user. The issue now is that we have no idea of the client window size, that means our picture could be look to the user ridiculy small, or too huge to be seen completely.

So we should rescale the image, and we can do that changing the height (part of the style attribute) for our image, referring to the clientHeight of the document body.

We create a function to do this job:

function resizeMe() {
document.getElementById("rock").style.height =
(document.body.clientHeight - 100) * 0.9;
}

We want call this function as soon as the page is loaded, so we put it in the onload attribute of the body tag:

<body onload="resizeMe(); greet();">
<!-- ... -->
</body>

It is worth noting that it is possible to insert code snippet as argument for the onload attribute, and not just the name of a function.

The attribute onload is the event handler called when the page is loaded for the first time, or reloaded by the user (clicking on F5, for instance). But what we can do to resize our image when the user resize the browser window? Easy solution: we use the onresize attribute:

<body onload="resizeMe(); greet();" onresize="resizeMe()">
<!-- ... -->
</body>

But beware: even if onresize is widely used, it is not (yet) a standard attribute. It should be part of HTML5.

Based on an example found in chapter three of Head First JavaScript, a good book for a new starter.

Go to the full post

Timeout rocks!

We can execute a JavaScript function after a specified delay using setTimeout(). If we want to run a function many times say, any 15 seconds, we can use setInterval().

Here we'll see how to use setTimeout() - setInterval() is quite the same, just remember that to stop it calling the associated function we could call clearInterval() - in an example that is meant to be an extension of the already seen basic JavaScript example.

The point of the code is that when we click on the picture, it is changed with a second one, but the new one shift automatically back to the default after a while (specified in millisecs):

<html>
<head>
<title>A whimsical page</title>

<script type="text/javascript">
var userName;

function greet() {
alert("Hello from a whimsical page!");
}

function setHappy(happy) {
var element = document.getElementById('rock');

if(happy) {
element.src = "image2.png";
element.alt = "Happy";
}
else {
element.src = "image1.png";
element.alt = "Bored";
}
}

function touchMe() {
if (userName) {
alert("I like the attention, " + userName + ". Thank you.");
}
else {
userName = prompt("What is your name?", "Enter your name here.");
if (userName)
alert("Nice meeting you, " + userName + ".");
}

setHappy(true);

setTimeout("setHappy(false)", 3000);
}
</script>
</head>

<body onload="greet()">
<div style="margin-top:100px; text-align:center">
<img id="rock" src="image1.png" alt="Bored" style="cursor:pointer" onclick="touchMe()" />
</div>
</body>
</html>


Post based on an example found in chapter three of Head First JavaScript, you should read it too, if you want more details, and some fun, too.

Go to the full post

Dozens of donuts

Another improvement to the Donut Manager we have wrote is about accepting donuts by dozens. Besides, we check also that the user won't input negative numbers as order.

To do that we will use the indexOf() method for a string, that returns the index where starts the specified substring in the current string. If there is no such a substring, -1 is returned.

We want to write a parseDonuts() JavaScript custom function that we would call in the update() to extract the number of donuts as input by the user, in this way:

var cDonuts = parseDonuts(document.getElementById("cdonuts"));
var gDonuts = parseDonuts(document.getElementById("gdonuts"));

If we have a "bad" value in the element, we reset the text to empty string. If we find "dozen" in the text we multiply the value by 12, and we write the actual value in the text:

function parseDonuts(text) {
var nrDonuts = parseInt(text.value);
if(isNaN(nrDonuts) || nrDonuts < 1) {
text.value = "";
return 0;
}
else if(text.value.indexOf("dozen") != -1) {
nrDonuts *= 12;
text.value = nrDonuts;
}
return nrDonuts;
}


Post written while reading chapter two of Head First JavaScript, a good book if you know nothing about JavaScript and not much about programming.

Go to the full post

Data validation for donuts

The JavaScript we wrote in the previous post is really basic. Let's improve it a bit adding some data validation.

We rewrite the placeOrder() function, to check any required field. So, name should not be empty, pickup should be a number, and the sum of the requested donuts should be greater than zero.

If we detect some non numeric data in a field that is expected to be numeric, we reset it to empty string:

function placeOrder(form) {

if(document.getElementById("name").value == "") {
alert("Your name is mandatory!");
return;
}

var pickup = document.getElementById("pickup");
if(pickup.value == "" || isNaN(pickup.value)) {
alert("Please, specify the pickup time");
pickup.value = "";
return;
}

var cDonuts = parseInt(document.getElementById("cdonuts").value);
if(isNaN(cDonuts)) {
cDonuts = 0;
document.getElementById("cdonuts").value = "";
}
var gDonuts = parseInt(document.getElementById("gdonuts").value);
if(isNaN(gDonuts)) {
gDonuts = 0;
document.getElementById("gdonuts").value = "";
}
if(cDonuts + gDonuts == 0) {
alert("Please, order at least one donut!");
return;
}

// Submit the order to the server
alert("Not implemented yet!");
//form.submit();
}


Post written while reading chapter two of Head First JavaScript, a good book if you know nothing about JavaScript and not much about programming. A bit too slow otherwise.

Go to the full post

Donut Manager

A simple JavaScript application to see the language in action. You can have a first approach to constants, variables, conversion from string to integer, the meaning of NaN, and how to specify the number of decimals for a floating point value.

Lot of stuff in a handful of lines.

To define a constant value in JavaScript we use the keyword const, it is costumary to give an all-uppercase name to a constant - C-style tradition.

A variable is introduced by the keyword var, notice that we let JavaScript deduce the type of the variable by the context.

To force the variable value to a specific type we should use standard JavaScript functions. For instance, converting a string to an integer value is done by parseInt().

We we try to get a number from a variable that does not contain such a value, we get a predefined constant, NaN (Not a Number). To check if a variable for NaN we use the isNaN() function.

Given a variable containing a number value, we can use the toFixed() method that we can call on the variable itself.

Let see how to use these concepts in an HTML page:

<html>
<head>
<title>Duncan's Just-In-Time Donuts</title>

<script type="text/javascript">
function update() {
const TAXRATE = 0.0925;
const PRICE = 0.50;

var cDonuts = parseInt(document.getElementById("cdonuts").value);
var gDonuts = parseInt(document.getElementById("gdonuts").value);

// avoid NaN
if(isNaN(cDonuts))
cDonuts = 0;
if(isNaN(gDonuts))
gDonuts = 0;

var subTotal = (cDonuts + gDonuts) * PRICE;
var tax = subTotal * TAXRATE;
var total = subTotal + tax;

document.getElementById("sub").value = "$" + subTotal.toFixed(2);
document.getElementById("tax").value = "$" + tax.toFixed(2);
document.getElementById("total").value = "$" + total.toFixed(2);
}

function placeOrder(form) {
// Submit the order to the server
alert("Not implemented yet!");
//form.submit();
}
</script>
</head>

<body>
<h2>Duncan's Just-In-Time Donuts</h2>
<p><i>All donuts 50 cents each, cake or glazed!</i></p>
<form name="orderform" action="donuts.php" method="POST">
<p>Your name: <input type="text" id="name" value="" /></p>
<p>C donuts #:<input type="text" id="cdonuts" onchange="update()" /></p>
<p>G donuts #:<input type="text" id="gdonuts" onchange="update()" /></p>
<p>Ext. pickup: <input type="text" id="pickup" /> minutes</p>
<br />
<p><input type="text" id="sub" readonly="readonly" /> Subtotal</p>
<p><input type="text" id="tax" readonly="readonly" /> Tax</p>
<p><input type="text" id="total" readonly="readonly" /> Total</p>
<p><input type="button" value="Place Order" onclick="placeOrder(this.form);" /></p>
</form>
</body>
</html>


Post written while reading chapter two of Head First JavaScript, a fun book to read.

Go to the full post

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.

Go to the full post

Cooperating Tags

This post has been moved to Biting Code, my blog dedicated to JVM languages.It shows how to write Simple Tags that work together in a JSP page.

Go to the full post

Simple tag for select-option

I moved this post to Biting Code, my blog dedicated to JVM languages.There you can find an example where a Simple Tag is used to implement a flexible generator of select-option HTML code.

Go to the full post

SkipPageException

This post has been moved to Biting Code, my blog dedicated to JVM languages.It shows how to control the failure in a SimpleTag throwing exceptions, and in particular a SkipPageException.

Go to the full post