I want to make a link call a Javascript function through the onclick event and not do anything else (follow the link). What is the best way to do that? I usually do this:
<a href='#' onclick='foo()'>Click</a>
But I’m not sure that is the best way and in this case it is navigating to page.html# which isn’t good for what I’m doing.
Usually, you should always have a fall back link to make sure that clients with JavaScript disabled still has some functionality. This concept is called unobtrusive JavaScript. Example… Let’s say you have the following search link:
You can always do the following:
That way, people with javascript disabled are directed to search.php while your viewers with JavaScript view your enhanced functionality.
Edit: As nickf pointed out in comment #2, a try and catch will prevent the link to follow if there is an error in your handler.