JavaScript offers the possibility to add interactivity to a web page. In other words, it allows the web designer to let the reader interact with the page by executing a script in the browser. The result of this interaction could be to update some content on the page, navigate to a new page, or open a window.
Typically, JavaScript interaction has been provided by way of a button control that can be clicked by the reader. For example:
<input type="button" value="Button Name" OnClick="javascript:MyFunction();">
</form>
This will produce a button on the web page, which might not be in line with the usability standards of the page.
As a general rule, users expect certain behavior from a button on a web page - it is usually a way to submit information to the web server. Now, it may be useful to be able to call a JavaScript function to validate the form, but the end result is still the same.
So, it should not be used for navigation, as this is not the behavior that the user expects.
Using JavaScript Links
To get around this, it is possible to create href JavaScript links that look like any other anchor text in the document. In this way, the behavior will be as the user expects, not to mention being tidier than having a web page navigation section (for example) consisting of buttons.
An href JavaScript link looks like the following:
In order to keep the code clean, it is advisable to put a call to a function in the href JavaScript link, rather than including all the JavaScript code inside the quotes. This means that a separate function to do the work must be included in the head of the document. This can be explicit:
<script language="JavaScript">
function MyFunction()
{
// javascript code
}
</script>
</head>
Alternatively, there could just be a reference to a .js file that is included from the head section:
This has the advantage of being separate from the HTML code that represents the page content.
It is also possible to perform the two actions in a single line of HTML - execute a piece of JavaScript, and go to a new page.
JavaScript Links and OnClick
This approach is useful in certain cases where it is necessary to update something on the client or server side (cookies, variables, etc.) and then go to a new web page which will use that information when it is displayed. The code uses the OnClick attribute, as follows:
If the href attribute is left blank, then to prevent the browser from trying to evaluate it, and coming up with a blank page error, the following is required:
It is the 'return false' statement that prevents the browser from following the invalid (empty) link. This is functionally equivalent to the first href JavaScript link example.
More JavaScript Tutorials
Those learning JavaScript programming might also be interested in:
Join the Conversation