Rafael Sanches

August 22, 2008

How to correctly make Javascript onclick links and keep in mind SEO and compatibility

Filed under: javascript, seo — Tags: — mufumbo @ 8:44 am

Today I have faced a common problem with web developers: How to correctly make Javascript onclick links keep in mind SEO and compatibility.

My solution was very simple, first of all, never use:

<a href="javascript:void(0)" onclick="some_function('someparameter')">Text</a>

This is the worst way of having javascript links. As discussed in this post this is a known issue of IE and why the use of the javascript pseudo-protocol for the value of HREF attributes is actively discouraged.

Suppose that you have an ajax box with tabs that allows you to refresh the content of the tabs with ajax. What would be the best way of assign onclick events to refresh the content with ajax?

What I did was:

  • When the page is loaded the first tab is loaded in the server side, without ajax. In this way search engines can crawl the contents.
  • The link on the tabs points to the HREF of the current page with a parameter that permits to change the pre-selected tab in the server side when the page is loaded. Ex: ?sec=onlineusers loads the page with the tab of onlineusers pre-selected and ?sec=lastusersers load the page with lastusers pre-selected.
  • The link on the tabs have the event onclick associated with a function and it returns false.

Code speaking:
<a href="?tabselection=onlineusers" onClick="changeTab('onlineusers');return false;">Online Users</a>
<a href="?tabselection=lastusers" onClick="changeTab('lastusers');return false;">Last registered users</a>

What are the advantages of this solution?

  • If the user have javascript disabled he can still have a fully functional website.
  • Search engines and mobile phones can navigate without problem.
  • It is compatible with all browsers.

For those who have already a website running, the simpliest way of having compatibility is to link the HREF to a page like “/noJavaScriptEnabled.html” and return false in the onclick event. Doing like this seems to be better than use the “javascript:void(0)” or point to the anchor “#”.

Blog at WordPress.com.

%d bloggers like this: