Call us

Using unobtrusive javascript to show and hide elements

Tutorials no comments yet

In this day and age of standards based design and web accessibility guidelines etc, it’s always a nice thing to get your websites to validate. Depending on which doc type you choose depends on how much work you have to do to get your site to validate.

One thing I have had to do recently was to get rid of an “onclick” Javascript event because it was the only thing stopping my website from validating. As this event was on every page of the website, I decided that I would look into an unobtrusive way to get round this problem.

I’ll say from the start that I am no Javascript expert so I came into a few problems. A great guy that helped me out was Jonathan Snook. I’ve had dealings with him in the past and I know him to be a bit of a Javascript guru so he was my first contact. Luckily for me he emailed me back with a pretty simple and great solution, so I will share it with you.

First, let me show you the website in question. Actually it was my main company website over at BPSDesigns. I have just finished a re-design of the site and incorporated a client “back end” so that my clients can log in and view their project progress, quotes and invoices etc. As you will see, there is a “Client Login” tab in the top right of the browser. This is where the onclick event was to drop down the client login form.

Basically you need some Javascript in your page to use the DOM to add the event to the “Client Login” image.

Here it is:

<script type=”text/javascript”>
window.onload = function()
{ /* we have to wait until the DOM has loaded before we can hook into it. */
var login = document.getElementById(’loginform’);
login.onclick = function()
{ /* lets do our thing when a user clicks on the Login title */
var target = document.getElementById(’login’);
target.style.display = target.style.display == ‘none’ ? ‘block’:'none’;
}
}
</script>

Explanation

The script is run when the page is fully loaded, then we hook into the DOM and get the id called “loginform” and attach our onclick event to it. Now we have an onclick event on the “Login” text inside the “loginform” div. Each time the “Login” text is clicked it toggles the layer on and off (or show and hide).
Note: if you want your mouse pointer to be a “hand” you will have to set that in your CSS because the mouse pointer will be the “pointer” otherwise. ie #loginform {cursor:pointer}

So your HTML will look something like this (simplified version)

<div id=”loginform”>Login</div>

<div id=”login” style=”display:none”>
Your login form goes here
</div>

And that’s it!

Thanks again Jon for your help on this one, I owe you one!

Related Posts

Leave a Comment