How To Use A Link To Call Javascript?
I think you can use the onclick
event, something like this:
<a onclick="jsFunction();">
<a onclick="jsfunction" href="#">
or
<a onclick="jsfunction" href="javascript:void(0);">
Or, if you're using PrototypeJS
<script type="text/javascript>
Event.observe( $('thelink'), 'click', function(event) {
//do stuff
Event.stop(event);
}
</script>
<a href="#" id="thelink">This is the link</a>
Unobtrusive JavaScript, no library dependency:
<html>
<head>
<script type="text/javascript">
// Wait for the page to load first
window.onload = function() {
//Get a reference to the link on the page
// with an id of "mylink"
var a = document.getElementById("mylink");
//Set code to run when the link is clicked
// by assigning a function to "onclick"
a.onclick = function() {
// Your code here...
//If you don't want the link to actually
// redirect the browser to another page,
// "google.com" in our example here, then
// return false at the end of this block.
return false;
}
}
</script>
</head>
<body>
<a ID="mylink" href="http://www.google.com">linky</a>
</body>
</html>
And, why not unobtrusive with jQuery:
$(function() {
$("#unobtrusive").click(function(e) {
e.preventDefault(); // if desired...
// other methods to call...
});
});
HTML
<a id="unobtrusive" href="http://jquery.com">jquery</a>
Unobtrusive Javascript has many many advantages, here are the steps it takes and why it's good to use.
the link loads as normal:
<a id="DaLink" href="http://host/toAnewPage.html">click here</a>
this is important becuase it will work for browsers with javascript not enabled, or if there is an error in the javascript code that doesn't work.
javascript runs on page load:
window.onload = function(){ document.getElementById("DaLink").onclick = function(){ if(funcitonToCall()){ // most important step in this whole process return false; } } }
if the javascript runs successfully, maybe loading the content in the current page with javascript, the return false cancels the link firing. in other words putting return false has the effect of disabling the link if the javascript ran successfully. While allowing it to run if the javascript does not, making a nice backup so your content gets displayed either way, for search engines and if your code breaks, or is viewed on an non-javascript system.
best book on the subject is "Dom Scription" by Jeremy Keith