Monthly Archives: January 2007

Dynamically Updating Text and its Color

For a current project, I’m putting together a form that among other things, allows people to input text and change the color of it, previewing their changes on the fly. It’s some basic javascript that updates the CSS and content. I thought I might share that one part of the form.

Let’s start without color-switching

Take color-switching out of the equation and just get content updates working first. I use this html:

<p>
<input
	type="text"
	id="inputText"
	name="inputText"
	value="Sample Text to Type" />
</p>
<p id="previewer" style="color:#000000;">
	Sample Text to Type
</p>

I have a basic text input to which I put the id inputText. I then put a paragraph beneath it with the id previewer. I need to use id’s as a way for the javascript to help identify these elements. Because I always want the input value to be the same as the paragraph text, I went ahead and put some filler text “Sampel Text to Type” in both places.

In English

I want to take whatever value is being typed into input#inputText, and insert it into the p#previewer.

The Javascript

function updatePreview() {
  var previewer = document.getElementById('previewer');
  var inputtxt = document.getElementById('inputText');
  previewer.firstChild.nodeValue=inputtxt.value;
}
 
function setText() {
  var inputtxt = document.getElementById("inputText");
  inputtxt.onkeyup = function() {
  	updatePreview();
  }
}
addLoadEvent(setText);

I’ll mention the second function first. “setText” finds the element with the id inputText and says “when someone lifts the key from they keyboard, update the paragraph (using ‘updatePreview’)”.

The “updatePreview” function takes whatever the value is on the input field, and inserts right after the opening <p> tag of id previewer.

The addLoadEvent statement makes this stuff happen when the page loads, and uses the addLoadEvent function, which I won’t cover here, but it is found in my example page.

Now change the color

Here’s the html:

<span id="colorselections"> 
  <a href="#" style="background-color:#000000;" class="on">
    <img src="space.gif" class="colorbox" alt="Black" />
  </a>
  <a href="#" style="background-color:#003399;" class="">
    <img src="space.gif" class="colorbox" alt="Light Blue" />
  </a>
  <a href="#" style="background-color:#5E5E5E;" class="">
    <img src="space.gif" class="colorbox" alt="Medium Gray" />
  </a>
  <a href="#" style="background-color:#00524E;" class="">
    <img src="space.gif" class="colorbox" alt="Dark Teal" />
  </a>
  <a href="#" style="background-color:#258B86;" class="">
    <img src="space.gif" class="colorbox" alt="Light Teal" />
  </a>
  <a href="#" style="background-color:#DA7E33;" class="">
    <img src="space.gif" class="colorbox" alt="Orange" />
  </a>
  <a href="#" style="background-color:#198541;" class="">
    <img src="space.gif" class="colorbox" alt="Green" />
  </a>
</span>

I start with a space of id colorselections. Inside it are lots of anchor tags leading to nowhere (#), styled with a background color. And each one calls a space.gif (I dusted off a spacer gif I had been saving in a drawer since 1997). It’s a transparent image that lets that background color show through. I can’t remember why I did it this way. But I did.

JavaScript for the color stuff

In English, when someone clicks on a color, take that color and assign it as the color to the preview paragraph, and also give an indication that color was selected by wrapping a border around it.

function updateTextColor(txtcolor) {
	var txt = document.getElementById('previewer');
	txt.style.color = txtcolor;
	return false;
}
 
// this function helps with the orange border around the 'on' color in the list
function clearColorSelections() {
	var colors = document.getElementById("colorselections");
	var choices = colors.getElementsByTagName("a");
	for (var i=0;i < choices.length;i++)
	{
		choices[i].className="";
	}
}
 
function setColor() {
	var colorselection = document.getElementById("colorselections");
	var links = colorselection.getElementsByTagName("a");
	for ( var i=0; i < links.length; i++) {
		links[i].onclick = function() {
		clearColorSelections();
		updateTextColor(this.style.backgroundColor);
		this.className = "on";
		return false;
		}
	}
}
addLoadEvent(setColor);

Starting with the last function, “setColor” loops through all the anchor tags found within the span colorselections, and adds an onclick event. When you click it, it will:

  1. Change all other colors to an ‘off’ state (this is just for styling purposes, since I use the orange border to indicate that a color is selected)
  2. Update the text color with the clicked anchor’s background Color. In CSS, you say “background-color”. In JavaScript, you say “backgroundColor”. No big whoop.
  3. Set the selected color to an ‘on’ state so I can wrap that orange border around it.
  4. return false. That means that I want to ignore href attribute and go nowhere, and for the browser to just ignore the fact that what I just clicked on was a hyperlink tag. If I leave this off, or set it to return true, clicking the color will try to go to “#”, which means top of the current page.

“clearColorSelections” will get ever <a> tag and set its class to nothing. (That way it won’t have the orange border).

“updateTextColor” takes the desired color and attaches it the the inline style for the paragraph previewer.

Summary

If this were a form, I’d need to find a way to pass the color selection. Semantically, I probably should’ve used radio buttons for the color selections, but I didn’t. In my real world scenario, I had some extra javascript that wrote the desired color to a hidden input field.

Knowing how to do this effect, you can see how easy it could be to have instant comment previewing on blogs, or better yet, create those browser-based word-processors and add “bold”, “italic”, and “underline” formatting.

Placing a Border Around a Thumbnail with a Form that Uses Radio Selection

I like how during the blogger sign-up process, while choosing a template, they offer clickable thumbnails of templates that work with their radio buttons. Here’s a way to do that.

The markup

I’m going to use an unordered list, label, and radio button.

<ul id="choicesList">
<li id="li-michael">
	<img src="images/michael.jpg" /><br />
	<label for="radiomichael">
	<input
		type="radio"
		class="radio"
		name="choice"
		value="michal"
		id="radiomichael" /> Michael
	</label>
</li>
<li id="li-madonna">
	<img src="images/madonna.jpg" /><br />
	<label for="radiomadonna">
		<input
		type="radio"
		class="radio"
		name="choice"
		value="madonna"
		id="radiomadonna" /> Madonna
	</label>
</li>
<li id="li-elvis">
	<img src="images/elvis.jpg" /><br />
	<label for="radioelvis">
		<input
		type="radio"
		class="radio"
		name="choice"
		value="elvis"
		id="radioelvis" /> Elvis
	</label>
</li>

Notice how the input is within the label. I just started doing this with my latest projects. I’ve yet to hear of any reason why one shouldn’t. This helps me meet my styling objectives while giving the added benefit of of having extra clickable space to activate the radio button for browsers that support it (all but Safari to my knowledge).

The main benefit of this technique is to have border around the selected item. In this case, all the li tags are styled to have a gray border by default. Once selected, that border turns green. If another radio becomes selected, then the first li returns to a gray border, while the newly selected radio will have a green border.

In order for the styling of the borders to change whenever a different radio button is selected, JavaScript is needed. By default, all li tags have a border of gray. When someone clicks on the image, I want JavaScript to insert class="on" to the li, and I will already have in my stylesheet that li.on will have a green border.

The JavaScript

I’ve realized that attempting to describe JavaScript functions can be a tricky thing in a blog. If it were just one function, I think I could get away with it, but because I’m using three main ones, it seems like any description could easily get lost in this narrative. For that reason, I’m going to do a very high-level description.

First there’s the “addLoadEvent” function, which allows me to have several functions load at a time. I use it all the time, not just with this particular effect.

Next is “clearChoices”. When I click on a new selection, how does the JavaScript know to remove class="on" from the previous choice? Using “clearChoices”, the JavaScript returns the classes on all the lis to normal, resulting in a default gray border.

“highlightChoices” first calls the “clearChoices” function above, then attaches the class of “on” to selected li tag.

When someone clicks an image, “imageClick” will make sure the corresponding radio button is checked, then highlights the surrounding li tag in green by calling “highlightChoices”.

Finally, there is “prepareChoices”, so if someone clicks the actual radio and not the image, the highlight effect still happens.


This post was ported from an old host and CMS, so many comments were lost. Below are the comments that I found were most helpful regarding this post that I salvaged. Some links or attributions may not be working correctly.


Peritus said:
You could’ve achieved the behaviour like this:
<li>
<label>
<img src=”images/michael.jpg” alt=””/><br/>
<input />
Michael
</label>
</li>
No Javascript needed ;)

@Peritus:
Yeah – putting the image within the label makes great sense.
I would still have needed javascript to change the list item’s border color.
Safari doesn’t treat labels the way most other browsers do – allowing the user to click the label to select the radio. In Safari, clicking the label doesn’t do diddly. For many developers and companies, though, Safari users are not priority.

Joe asks the CSS Guy for a book recommendation

Joe R. writes:

I’m a web designer for a fairly large company, but keep getting detracted from doing my web work by things like “business development”, “client relations”, and the like. I mean, I guess my boss decided that in addition to maintaining the company’s website, I should be able to do other stuff as well. Anyway, in all this commotion, I haven’t been able to spend nearly as much time as I’ve wanted to learning the ins-and-outs of CSS (which is my current most favorite thing).

I’m pretty much a novice with CSS, but every day I scour the Internet for any tips and tricks I can get my hands on. My question to you is this: if you could recommend one book for a novice CSS-er, what would it be?

Joe, I’m flattered you’d ask. I understand how a web designer has much more to do than just design all day. I’ll offer you what I know, but it may not amount to two cents. For this reason, I’d like to open your question up to others, who I hope wouldn’t mind telling what book helped them most.

I’ve only read two books related to CSS – Designing with Web Standards by Jeffrey Zeldman and Web Standards Solutions by Dan Cederholm. The rest of my education is spent doing what you do – scouring the internet to see what other people have done.

Both of those books excellent and helpful. I read Zeldman’s first edition at a time when I was just starting to explore CSS. Because of that timing, it stirred an excitement and motivation in me to change my approach to design from thinking in tables and images to thinking in web standards. It’s not about the latest tricks – it’s about migrating to something versatile, accessible, and future-proof, and it’s a very introductory-level book. If you find yourself in a similar spot, I cannot give Zeldman’s book a high enough recommendation.

Whereas Zeldman’s book felt about 50% how-to and 50% why-to, Cederholm’s book seemed to focus more on the how-to. I think the book is great for those who are convinced to do all-CSS based layouts and know the basics, but want to get a little more in-depth with what can be done with various bits of code. I personally felt like I picked up Cederholm’s book a tad too late, as even though it gave me plenty more to think about, I felt like I had already learned much of it already. Still, it’s part of my collection, and I’m proud to have it.

Readers, have you any suggestions for Joe?


This post was ported from an old host and CMS, so many comments were lost. Below are the comments that I found were most helpful regarding this post that I salvaged. Some links or attributions may not be working correctly.


Cesar said:
Here are some other great CSS books that I would recommend reading as well The Best-Practice Guide to XHTML and CSS by Patrick Griffiths of Vivabit and Transcending CSS: The Fine Art of Web Design by Andy Clarke and Molly E. Holzschlag of Stuff and Nonsense and Molly.com respectively.
The Best-Practice Guide to XHTML and CSS is a great primer and reference guide to proper web standards coding while Transcending CSS: The Fine Art of Web Design is an additional discussion based book on the future of web design and CSS.

cody lindley said:
My two cents…
This book should be the go to book (Beginning CSS, Apress) for those interested in learning CSS.
Once you have read this book, buy A Definitive Guide on CSS and consider purchasing CSS Mastery or Pro CSS Techniques for advanced CSS topics.

omar said:
I only have two. The better of the two is the CSS Mastery book linked by cody above.
The one that got me up to speed was Teach Yourself CSS in 10 Minutes. It’s not a book that will teach you all kinds of cool CSS tricks, but it’s a good (and cheap) book for learning the basics. I got it over a year ago, and I still reference it regularly.

Lorissa said:
I’ll definitely second the recommendation for Dan Cedarholm’s Web Standard Solutions. His second book, Bulletproof Web Design is excellent as well. Both are well worth it.
Sounds like I need to get my hands on CSS Mastery though.