HTML (HyperText Markup Language) Anchor tags (or hypertext links) form a vital part of every web site - they provide the inter-connectivity between web pages. In addition, anchors are more than just a means of moving between web pages - they can also give a means of running Javascript code within a web page. However, a programmer can simulate all of the functionality of the anchor by using Javascript code.
Using Anchors in a Web Page
The most common use for an anchor in a web page is as a link to another web page:
and to set up links to other sections within the same web page:
or even to send an email:
Finally, an anchor can also be used to run Javascript code.
Using Anchors to Run Javascript Code
Running Javascript from an anchor is very simple - it's just a matter of setting the href property with the Javascript code instead of a web page address:
However, the Javascript programmer can turn any portion of the web browser into an anchor.
Simulating an Anchor with Javascript
The starting point for the Javascript anchor is a web page object with an id, for example:
In this example a font object is being used but it could just as easily be an image, a head tag or even a whole paragraph. Whichever object is to be used the technique is the same - and the first step is to select the pseudo-anchor object:
Traditionally anchors are blue and underlined and that's easily achieved with Javascript:
One thing that may give pause to think is the mouse pointer - when that's placed over an anchor it will normally turn into an image of a hand with a pointing finger. Fortunately that's no more difficult than changing the text color:
new_link.style.cursor = "pointer";
Finally, and most importantly, the new anchor will need some functionality assigned to it - functionality that will run when the user clicks on the pseudo-anchor:
This will run the anchor_action function which, of course, still needs to be written and which will move the user to another web page:
or to move about within the same page:
In this way the Javascript programmer can simulate an HTML anchor.
Summary
A standard HTML anchor allows a web page user to:
- move between web pages
- move between sections on the same web page
- create emails
- run Javascript code
Using these techniques, the Javascript programmer can simulate all of the anchor functionality for any object on a web page.