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.


 I'll keep this short and sweet.  You're probably familiar with the anchor tag, or 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:



 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 also try to navigate away from the page. 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):


 


 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 container, which we'll locate inside the container (this is standard, but it's not the only place we could have put it).  Our script container and function look like this:


    


        function myAlert(){


            alert("You clicked me!");


        }


   


 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!

 •  0 comments  •  flag
Share on Twitter
Published on June 14, 2011 20:37
No comments have been added yet.