Blog Post RSS ?

Blogs » JavaScript & CSS » Easy bulk changes with DHTML
 

Easy bulk changes with DHTML

by Simon Willison

Andy Clarke has published a neat new technique called Trimming form fields, which uses beautiful unobtrusive DHTML to allow users to toggle the visibility of optional form fields for easier completion of forms. Andy’s code is very tidy and you should go and read his tutorial, because I’m about to extend on it.

Andy’s code works by cycling through each div on the page, looking for those with class fm-optional and toggling their display value. This works just fine, but there’s actually a more effective way of achieving the same effect. Instead of toggling a whole bunch of individual elements, change the class on an element that contains all of those that you wish to toggle and use a simple CSS selector to target the contained elements.

I’ve demonstrated this alternative technique on this page (adapted from Andy’s example). Here’s the CSS:

form.remove div.fm-optional { display: none; }

And the link event handler:

toggle.onclick = function() { if (/remove/i.exec(this.firstChild.nodeValue)) { this.firstChild.nodeValue = 'Display optional fields?'; document.getElementById('example-form').className = 'remove'; } else { this.firstChild.nodeValue = 'Remove optional fields?'; document.getElementById('example-form').className = 'display'; } return false; }

The above code could certainly be improved – for example, it doesn’t deal with the possibility of the form having one or more existing classes that need to be maintained. It serves as a useful demonstration of how bulk changes can be made to a document by switching just a single class on a containing element.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Ping.fm
  • Twitthis

Related posts:

  1. Techy Treasures #4: What’s inside a dollar function? The $ function is a common feature of all of...
  2. Implementing Event Latency in JavaScript Craig provides some useful JavaScript code to slow down event...
  3. The Two Ways of Sizing Absolute Elements in CSS Most developers have used left, right, top and bottom properties...
  4. Styling the html and body Elements One of the most common ways to begin a...
  5. The 5 Most Under-Used HTML Tags It is easy to forget some of the lesser-known HTML...

This post has 4 responses so far

Sponsored Links

SitePoint Marketplace

Buy and sell Websites, templates, domain names, hosting, graphics and more.

Follow SitePoint on...