Powering Javascript UI with CSS

| No Comments | No TrackBacks

If you have been doing any Javscript coding during the current Javascript renaissance, you will have noticed that a lot of the user interface functionality you build is hiding and showing things.

After a while of this you might find yourself coding up toggle functions, which find elements and toggle their visibility. togglePair, toggleVisibilityById, there are lots of these types of functions in javascript apps today.

I've been trying out a different way of dealing with the need to change the UI based on user inputs or asynchronous data events: CSS.

With CSS, you can use the DOM as a data model and then use declarative rules to establish the display. It's cleaner, because you limit your javascript code to changing the DOM's data instead of it's UI, and then you use the extensive abilities of CSS to handle the visual representation of that data.

Here's an example. A common thing to do with javascript seems to be expanding out a form to fill out. Livejournal does this with their login form, or 37Signal's tadalist uses this when you want to add an item to your todo list.

here's the just javascript way to do this:

<div>
<span onClick='document.getElementById("form1").style.display="block";'>click me to add a comment</span>
</div>
...
<form id='form1'>
<textarea>add your comment</textarea>
</form>

But here's the CSS + Javascript way to do it.
CSS Rules

form#addComment {

display:none;

}

form#addComment.editing {
display:block;
}

Javascript + HTML

<div>
<span onClick='document.getElementById("addComment").setAttribute("class","editing");'>click me to show form</span>
</div>
...
<form id='addComment'>
<textarea>fill in some data here</textarea>
</form>

This can prove really advantageous when you are radically changing the visual presentation of the page. Instead of finding and changing the style of tons of elements by id, you can change 1 element's class and then use the inheritance of CSS to style all the sub-elements.

No TrackBacks

TrackBack URL: http://www.wujianrong.com/mt-tb.cgi/2577

Leave a comment

相关文档

上一篇:10个你必须用到Ajax的地方[转] .

下一篇:FeedSky停了?