0

I am making my first responsive design website.. I have an image slider div that is set with using pixels and media queries. I want to be able to access the width so I can tell the image slider how far I need to move. Unfortunately media queries don't seem to change the HTML. Is there any workarounds to get that information so I can use it in javascript.

here is a simple webpage example to play with and a JSFiddle http://jsfiddle.net/synthet1c/sNbW9/

<!doctype html>
<html>

<head>

<style>

    body{
        position:absolute;
        background:red;
        width:100%;
        height:100%;
    }

    #outer{
        position:absolute;
        width:80%;
        height:80%;
        background:red;
        background-image:url('http://www.largepictures.net/largepictures/scenery/largepictures_scenery_large_3066.jpg');
        background-position: center;
        margin:auto;
    }

    #inner{
        width:80%;
        height:80%;
        background:rgba(255,0,0,0.3)
        margin:auto;
        margin-top:5%;
    }

</style>

    <script>

    document.getElementById('inner').onclick = function(){
        alert(document.getElementById('inner').style.width);
    }

    </script>   

</head> 

<body>

    <div id="outer">

        <div id="inner">click the box to get width</div>

    </div>

</body>
</html>

3 Answers 3

1

The element.style object is only available for properties set with the style attribute (as the name might suggest). To retrieve CSS settings for elements whose style is set using a stylesheet:

document.getElementById('inner').onclick = function(){
    alert(window.getComputedStyle(document.getElementById('inner'), null).width);
}

JS Fiddle demo.

References:

Sign up to request clarification or add additional context in comments.

Comments

0

I made a little snippet for myself as this is a function I have been needing for a while

var comStyle = function(element , pseudoElt){ 
    if(!pseudoElt){pseudoElt = null} 
    return window.getComputedStyle(document.getElementById(element), pseudoElt); }

This has me thinking though... Am I able to change the prototype so if element.style.something equals and empty string then use getComputedStyle() to get the actual value from the stylesheet?

Comments

0

Can't you just use offsetWidth, it's read-only property providing width of an element as an integer.

var el = document.getElementById('inner')

el.onclick = function(){
      alert(el.offsetWidth)
}

http://jsfiddle.net/t2r7jnb4/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.