Craig Francis


JS Linked Widget

If you need to hide part of a page, but have it displayed when a user requests it, you can use this bit of unobtrusive JavaScript.

Example

This code allows the page to have a link which shows and hides a hidden element.

Such as this paragraph... which also contains a close link.

The code

First you need to download my script.js and linkedWidget.js files and include them in the pages <head>, like so:

<script type="text/javascript" src="scripts.js"></script>
<script type="text/javascript" src="linkedWidget.js"></script>

Then add a simple link which anchors to the element you want hidden by default, and add the 'jsLinkedWidget' class, like so:

<p><a href="#targetId" class="jsLinkedWidget">Open</a></p>
<p id="targetId">Hidden text</p>

If you want a 'close' link in the hidden element, then you can add a link which anchors to '#' with the 'jsLinkedWidget' class, like so:

<p><a href="#targetId" class="jsLinkedWidget">Open</a></p>
<p id="targetId"><a href="#" class="jsLinkedWidget">Close</a></p>

Dependancy note

You don't really need the full scripts.js file, as we only use the addLoadEvent and cssjs functions. But it does contain other functions which are handy to have lying around.

Known issues

The hidden element is toggled using an onClick event, this is not really considered best practice when it comes to keyboard users who would also like an onKeyPress - however it does seem to work.

When the onClick event triggers, it does a 'return false'... This means that the link appears to be broken for screen reader users, who expect the link to load a new page. It is possible to remove this 'return false', but it causes the screen to visually jump in some browsers, which can be disorientating for users.

Any feedback would be greatly appreciated. If you would like to use this code, please read the licence it is released under.