View Full Version : Can't get margin-left property value

01-22-2012, 12:24 AM
When I click on the image I want to get the "margin-left" value of its block.
In the code below the margin-left is set at 100px.
But when I click on the image the "margin-left" value shows in the "alert" as undefined.
What code changes do I need to get the correct margin-left value?
(Please, no guessing!)

<script type="text/javascript" >
window.onload = function(){
document.getElementById("holder").onclick = showit;

function showit( ) {
var marval = document.getElementById("holder").style.marginLeft;
alert(" margin-left= " + marval + " typeof= " + typeof marval);

<style type="text/css">
padding: 0px;
margin-left: 100px;
<img id="holder" src="anyimage.gif" width="300px" height="200px" />

01-22-2012, 05:24 AM
To read inherited style properties, defined in style sheets,
(as opposed to those set as inline html style attributes,)
use the computed style of the element.

Older IE's use one method, other browsers use another.
It can be an expensive method, so check for an inline style first.

You can sort out one method to call, and then use it as often as needed.

window.getComputedStyle= function(elem){
return elem.currentStyle;
function deepC(elem, css){
if(typeof elem== 'string') elem= document.getElementById('elem') || '';
css= css.replace( /\-([a-z])/g, function(a, b){
return b.toUpperCase();
if(!elem.style) return '';
return elem.style[css] || getComputedStyle(elem, '')[css] || '';

alert(deepC('holder'), 'margin-left'))

01-22-2012, 09:42 PM
I was unfamiliar with the getComputedStyle method.
You have headed me into a new DOM territory.
For that, and your solution, I am truly grateful.