Archive for the 'JavaScript' Category

Sep 02 2006

Changing Text Using innerHTML

A lot of people have sent kind comments about the post regarding the technique to expand and collapse blocks of HTML. McKack asked how to change text or an image source from within [div] tag. Since the original post helped so many, I thought I’d post a solution to the first part of McKack’s inquiry. I’ll provide a snippet for the second part in a separate post.

There are dozens of ways to dynamically change the text on a web page using JavaScript. One way is to hide and show the contents of tags, as described in that first post. Another way is to use the innerHTML property:

innerhtml1.gif
[Download Snippet]

This example simply takes the contents of a form field and shoves it inside an HTML element, in this case a [div] block. It’s really that simple. Note that you can use innerHTML to set the contents of an element to anything that makes sense. That is, the content does not necessarily have be just text, it can be HTML elements, too.

No responses yet

May 22 2006

Expand/Collapse Blocks Using CSS Display Property

Having to write code to different browsers and platforms is a pain in the arse. I am constantly finding myself having to write alternative versions of some JavaScript function to work with either Inetrnet Exploder or Netscrape. In some cases I have even written different versions of a function for the same browser on different platforms.

One particular problem we (the developers at CRS, my employer) have been struggling with is dynamically showing or hiding a block of HTML inside of either a <div> tag or a table row. Since our application is used primarily by PC users running Internet Explorer, we had been using something like this to dynamically expand and collapse blocks:

collapseexpande_bad.gif
[Download Snippet]

This works in Internet Explorer, but behaves strangely in most other browsers. I won’t get into the details of how each browser handles the code. What we want is a solution that works with all browsers. Right?

Right. I’m embarrassed that I dragged my feet for so long to fix this, writing stupid workarounds for browsers other than PC-IE. The problem in the code snippet above is not the JavaScript, but the block value used for the display property. For a block to expand and render properly, the value of the property should be set to an empty string in the JavaScript and in the HTML. Also, notice the difference in the style attribute of the div tag. The value of the display property is an empty string there as well, without quotes. Qualifying property values in inline styles is common but incorrect and will cause problems.

collapseexpande_ok.gif
[Download Snippet]

No responses yet