views:

35

answers:

4

Take a look at this example code, which doesn't work:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;

<head>

<script type="text/javascript">
<!--

function moveMe() {
        document.getElementById('moveme').top = 200;
        document.getElementById('moveme').style.backgroundcolor = 'green';
        document.getElementById('writeme').innerHtml = 'abc';
        alert('called!');
}


// -->
</script>


<style type="text/css">

.moveable {
    position: absolute;
    top: 30px;
    left: 200px;
    width: 100px;
    height: 100px;
    background-color: yellow;
}

#writeme {
    background-color: red;
    color: white;
}

</style>


</head>

<body>

<div id="moveme" class="moveable" onClick="moveMe()">
<p id="writeme">Hello!</p>
</div> 

</body>

</html>

When I click on the text the alert is displayed, but nothing is changed in the document. The paragraph text is not overwritten, the div is not moved... tested it in FF and IE, also checked the DOM via Firebug: strange thing is that the new values are written to the nodes, but they are displayed in bold, and the old values are still there. WTF?

I guess I'm missing something fundamental here.

+5  A: 
  • Non-zero lengths require units, "200" is missing its unit
  • JavaScript is case sensitive: backgroundColor and innerHTML
  • Since you appear to be using XHTML, your script is commented out
David Dorward
Thanks everyone, that was superquick!Even though uncommenting the script doesn't seem to matter, that's a good article.
Gabor Kulcsar
+2  A: 
  document.getElementById('moveme').top = 200;

needs to be

  document.getElementById('moveme').style.top = "200px";

I think; and

  document.getElementById('writeme').innerHtml = 'abc';

needs to become

  document.getElementById('writeme').innerHTML = 'abc';

and it's backgroundColor with a capital C as @David spotted first.

Pekka
A: 

Try this:

<script type="text/javascript">

function moveMe() {
        document.getElementById('moveme').style.top = '200px';
        document.getElementById('moveme').style.backgroundColor = 'green';
        document.getElementById('writeme').innerHTML = 'abc';
        alert('called!');
}

window.onload = moveMe;

</script>
Sarfraz
A: 

Additionally to what the others said: Drop the <?xml version='1.0' encoding='UTF-8' ?> , because that puts IE in Quirksmode.

RoToRa
Only IE6, and that would actually work to the benefit of the broken code (units aren't required in Quirks mode)! This answer really should have been a comment.
David Dorward