I've been learning javascript and one thing I was trying to accomplish was designing some good encapsulated javascript functions for my code. The code is as follows:
<html>
<head>
<title>Test, Proof of Concept</title>
<style>
div.ball {
content:url(http://upload.wikimedia.org/wikipedia/en/e/ec/Soccer_ball.svg);
float:left;
width:50px;
height:50px;
position:absolute;
top:20px;
left:20px;
}
</style>
</head>
<body>
<div style="width:600px;height:600px;background-color:#3366CC" id="canvas">
<div class="ball" id="ball">
</div>
</div>
<script>
function getProperty(elementId, property) {
return document.getElementById(elementId).style[property];
}
function setProperty(elementId, property, value) {
document.getElementById(elementId).style[property] = value;
}
(function() {
//setProperty("ball", "top", String(200 + "px") );
/* If I include the line above, the code suddenly works as expected. */
var topVal = parseFloat( getProperty("ball", "top").replace("px","") );
setProperty("ball","top",topVal + 100);
})();
</script>
</body>
</html>
As indicated by the multi-line comment in my code, the code will work if I include that commented out line. I think I understand why the code will not work without that line (something about my CSS code at the top of the page setting the "top" and "left" attribute to the client object and not the object with the id 'ball'?) but I have no clue how to get my code to work without including it.
Could I get some insight about the mistake I am making in regards to my assumption about how CSS works, and how my code can be made to work without the commented out line?
I really appreciate your time :)