JavaScript: calling events inline

March 13, 2009 / Filed under: JavaScript, PHP, HTML

There are a few different ways to call events in JavaScript - the most popular being as inline attributes. There is often some confusion surrounding the proper way to designate JavaScript events inline, while maintaining application composure if JavaScript is turned off.

The most commonly used approach looks something like this:

<a href="#" onclick="my_function()">Link</a>

Here we use a "pound" or "hash" character as the href value. This is because we need to put something in there, but we only care about the onclick event firing. Turns out this is not the best approach because it fails to do anything if JavaScript is turned off.

Ideally, you should provide a real location as the href value:

<a href="page.htm" onclick="my_function(); return false;">Link</a>

The above approach is safer, because if JavaScript is turned off, the browser will simply go to page.htm, and ignore the onclick attribute.

my_function() could then look something like this:

function my_function()
{
    window.location = "page.htm";
}

With JavaScript turned on, the browser acknowledges the onclick attribute. We also add return false; inline, so the link does not go anywhere until we explicitly tell it to within the my_function function. This is useful in case there are reasons we'd like to stop the link from working - perhaps there is a user-submitted error on the page that needs to be corrected before proceeding.

Same for

This approach should be consistent when handling HTML forms.

<form method="post" action="page.php" id="my_form" onsubmit="validate(); return false;">

Again, if JavaScript is turned off, the form submits to page.php right away, where we'd process the form details. If JavaScript is turned on, we first run a validation function to ensure the form values are accurate before submitting to the server:

function validate()
{
    var my_form = document.getElementById("my_form");

    my_form.submit();
}

Here we submit the form via JavaScript, but only if it's passed all of our validation tests. If not, we just don't run this line:

my_form.submit();

If that line is not run, the function will return true, then it will see the return false; inline, and stop everything. This is what we want, because we want to stop everything if the form should not be submitted.

Keep in mind, when handling submitted form data, you should always validate both client and server side. So, even if they pass the JavaScript validation tests, those same checks should be applied in the PHP page.

Comments/Mentions

Your comment
Your info
Update Twitter

Tweet this


140/140 characters remaining

To quickly post about this on Twitter, sign in to Twitter first using the button on the left. Then, confirm that you'd like to allow this site to update your Twitter status. You'll be able to edit your tweet before submitting, and your tweet will show up on this page as another comment.


Spam check