PDA

View Full Version : Can someone correct this?



quint
05-11-2007, 06:00 AM
I was messing around and wrote this little script (below). I thought what it would do is onclick write "Hello World!" beneath the links, but it is overwriting the links themselves.

Can someone please explain what I would have to do to get it to write "Hello World!" beneath the links and in the color selected onclick?

Thanks,

~q

---------------------

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<script type="text/javascript">
function message(color){
if (color == 'r')
{
document.write("<P><h2><font color=red>Hello World!</font></h2>")
}
else if (color == 'g')
{
document.write("<P><h2><font color=green>Hello World!</font></h2>")
}
if (color == 'b')
{
document.write("<P><h2><font color=blue>Hello World!</font></h2>")
}
}
</script>

</head>

<body bgcolor="#FFFFFF" text="#000000"><p>
<a href="javascript:message('r')">Red</a> <a href="javascript:message('g')">Green</a>
<a href="javascript:message('b')">Blue </a> </p>
<P>
<script type="text/javascript">
function message(color){ }
</script>
</body>
</html>

jscheuer1
05-11-2007, 06:34 AM
You cannot document.write to the page once it is loaded without overwriting it. There are various ways to carry out what you seem to want to do (which in itself isn't entirely clear). Here's one:


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
#hding {
display:none;
}
</style>
<script type="text/javascript">
function message(color){
var h=document.getElementById('hding').style;
h.color=color=='r'? 'red' : color=='g'? 'green' : 'blue';
h.display='block';
}
</script>
</head>
<body>
<div>
<a href="javascript:message('r')">Red</a> <a href="javascript:message('g')">Green</a>
<a href="javascript:message('b')">Blue </a>
</div>
<h2 id='hding'>Hello World!</h2>
</body>
</html>

quint
05-11-2007, 08:59 PM
Perfect. :)

Thank you, John!

If there are any tuts on alternate techniques for this, then I'd love to see them.

Thank you again.

~q

jscheuer1
05-12-2007, 06:04 AM
Well, the techniques used are more or less basic javascript techniques. It is just a question of organizing them in a sensible manner to accomplish the goal. w3schools.com has decent javascript tutorials.

Twey
05-12-2007, 09:42 AM
It contains some misinformation, though, and doesn't always make clear whether a technique is standard or proprietary. I prefer to link people to the howtocreate.co.uk tutorial (http://www.howtocreate.co.uk/tutorials/javascript/important) now.