Anchors Away

Yes, I know, you sailors out there, the phrase is “Anchors Aweigh,” the fight song of the US Naval Academy, but this is about HTML — not maritime navigation, submarine-launched missles, or Top Gun. 

I’ll keep this short and sweet.  You’re probably familiar with the anchor tag, or <a> tag, as a way to insert a hyperlink into your markup document.  You may even know that it can also be used to create a bookmark.  But did you know you can use it to call a JavaScript function to “do nice things”?

 Check out this markup:

<a href=””>Click me</a>

 Not very noteworthy, huh?  Won’t do anything, you say.  On the contrary, it will do something, but not anything you’d want it to do.  It has no hyperlink for the href attribute, but if you click it, it will still try to navigate off the page.  Not at all useful.

 Look at this modification:

<a href=”” onclick=”myAlert()”>Click me</a>

 If we had a JavaScript funtion called myAlert(), this code would call it and execute whatever code the function contained.  At this point, we are definitely dealing with code and not markup, but I’ll keep it simple.  The problem, however, is that the browser still tries to navigate away from the page. Never fear; there is a fix for this. I’ll show it here, but I won’t try to explain it.  For now, just use it and trust (or some may wish to Trust but Verify):

 <a href=”” onclick=”myAlert(); return false”>Click me</a>

 Technically, the “onclick” is known as an event, and the function it refers to is the event handler.  So, let’s create that event handler.  We’ll need a place to put it, and that will be inside a <script></script> container, which we’ll locate inside the <head></head> container (this is standard, but it’s not the only place we could have put it).  Our script container and function look like this:

     <script type=”text/javascript”>

        function myAlert(){

            alert(“You clicked me!”);

        }

    </script>

 This is the complete code, everything you need to create a popup alert that says, “You clicked me!” and inhibit navigation away from the page.  You can put as much code as you want in the function, but that is left as an exercise for the reader.

 There is one more issue to discuss.  Oftentimes your browser will block any JavaScript popups.  If this happens, click the warning bar and allow the operation to continue.  You might be able to change your security settings to prevent this from occuring, but it’s probably not worth it, and that’s out of the scope of this discussion, anyway.

 That’s it.  Try it!

This entry was posted in Horton's html hints. Bookmark the permalink.

Leave a Reply