PDA

View Full Version : Setting margin issue



Dhuan
Jan 15th, 2010, 10:31 PM
<script>

function myfunction(){

document.getElementById('myDIV').style.marginLeft++;

}
</script>



<body>



<div id="myDIV">
This is a DIV...
</div>

<p>

<a href="javascript:myfunction()">Do it!!</a>

So, what this code is supposed to do is, every time the user click on 'Do it!!', the 'myDIV' div goes to the right. The problem is, it works only one time, why?

Dormilich
Jan 15th, 2010, 10:38 PM
actually, I can’t get it to work even once, due to marginLeft++ not having a unit. you would expect something like "1em" or "10px", but I only get "" (well, that happens, when you try to increment a string …)

I had to get the CSS differently

function shiftLeft()
{
var m = window.getComputedStyle(this, null).getPropertyCSSValue('margin-left').cssText;
this.style.marginLeft = (parseInt(m)+10) + "px";
}
document.getElementById("myDiv").addEventListener("click", shiftLeft, false);