Dynamic Text Boxes
If you've got lots of images on one page with a description for each — or even multiple layouts/skins that visitors can choose from that need detailing — you probably won't want long lists of text that the visitor has to scroll through to find the part that applies to them. Instead, why not have one box for text and allow the users to control what text is display? We can do this with a little JavaScript.
First we need our images and a box, or <div> for the text to appear in. We need to assign this an id, so that the JavaScript knows which element we're referencing. This is roughly what our HTML will look like:
<p><img src="an-image-here.gif" alt="image" /></p> <div id="textbox"> </div>
Now we need the JavaScript function which actually tells the browser what to do with our text box, and your text. We'll use getElementById(), which will allow us to manipulate HTML elements based on their assigned id. The function, which belongs in the <head> of your document, is as follows:
<script type="text/javascript">
function getText(inputtext) {
document.getElementById("textbox").innerHTML = inputtext;
}
</script>
Because our function is now ready we can build it into our page and apply the new getText() to our HTML from above — my favoured event handler for this is "onmouseover" so that we don't need to click to view the text. Our finished code example will now look like this:
<html>
<head>
<title>my javascript dynamic text box script</title>
<script type="text/javascript">
function getText(inputtext) {
document.getElementById("textbox").innerHTML = inputtext;
}
</script>
</head>
<body>
<p><img src="an-image-here.gif" onmouseover="getText('SOME TEXT HERE');" alt="image" /></p>
<div id="textbox"> </div>
</body>
</html>
For each image we have, we apply the getText() function inside onmouseover, replacing SOME TEXT HERE with the text you want to display in the box when the user hovers over the image. Easy as pie.
Tags:
javascript, getelementbyid, onmouseover,
Last Updated On: 25th June 07 by Jem
Bookmark At: StumbleUpon, Digg

Handy Stuff
Downloads
Friends of 'TT'
Resources