Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Jan 2012
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Unhappy Can't get margin-left property value

    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!)

    [CODE]
    <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);
    }
    </script>

    <style type="text/css">
    #holder{
    padding: 0px;
    margin-left: 100px;
    }
    </style>
    </head>
    <body>
    <img id="holder" src="anyimage.gif" width="300px" height="200px" />
    </body>
    [CODE]

  • #2
    Regular Coder
    Join Date
    Mar 2006
    Posts
    728
    Thanks
    35
    Thanked 132 Times in 123 Posts
    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.


    Code:
    if(!window.getComputedStyle){
    	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'))
    Last edited by mrhoo; 01-22-2012 at 05:44 AM.

  • Users who have thanked mrhoo for this post:

    Cheldark (01-22-2012)

  • #3
    New to the CF scene
    Join Date
    Jan 2012
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts
    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.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •