CIT041J Index > Lecture Notes - Part 3

CIT041J Lecture Notes - Part 3

More about Invoking JavaScript

In older books and web sites, you may see code like this to invoke JavaScript from a link (which you may try here: Say Hello)

<a href="javascript:alert('hello')">Say hello</a>

This works, but will cause problems for people whose browsers don’t understand JavaScript. The “approved method” for invoking JavaScript in a link is the way we have done before:

<a href="#" onclick="alert('hello')">Say hello</a>

There is a problem with this method, however. When JavaScript is active, what will happen is that the browser will do the onclick actions, and then take the href jump back to the top of the same page. Make the window smaller, so that you have to scroll this link that does the greeting: say hello. For someone who doesn’t have JavaScript active, the browser will just jump to the top of the page, which tends to mystify users.

Let’s fix the problem for the person with JavaScript active, by adding the code in bold to the onclick handler:

<a href="#"
   onclick="alert('hello'); return false;">Say hello</a>
Say hello the right way

When you click this link: Say hello, The browser will first call the onclick code. The return false tells the browser that it should not continue the normal process any further, and should not take the href jump to the top of the page.

What about the person with JavaScript inactive? Rather than simply go back to the same page, you should have a link to a page explaining why the desired result didn’t occur. Here’s such a link: Say hello

<a href="no_js.html"
   onclick="alert('hello'); return false;">Say hello</a>

The <noscript> element

You can also put messages inside a <noscript> element. They will show up only if JavaScript is disabled or unavailable.

Prompting for input

In the previous notes, you saw a function that calculated the age in days for 12-year-olds. Ideally, you would like to get user input. In the next notes, you will see how to do this with a <form>. But for now, you can use the prompt() function in JavaScript. This function takes two parameters: the text for the prompt, and a default input value. When invoked, it puts up a dialog box prompting the user for input (hence the name).

The return value of the function is the user input, or the special value null if the user clicked the Cancel button.

Here’s the code for the new show_age function, and here is a link for you to try out.

function show_age( )
{
   var years = prompt("How old are you? ", "");
   if (years == "")
   {
      alert("You didn't give me any input!");
   }
   else if (years == null)
   {
      alert("Why did you cancel on me? I'm heartbroken!");
   }
   else
   {
      result = calc_age( years );
      alert(years + " years is " + result + " days old.");
   }
}