0

I'm trying to use JavaScript to change the width of a div, but something's wrong with one part of my code. I think it's this part:

document.getElementById("div").style["width"] = width+"px";

I'm not sure what's wrong with it, so if you know, please let me know. Thanks.

<script>

function adapt (percentage) {

var width = percentage/100;
var width = window.innerWidth*width;

document.getElementById("div").style["width"] = width+"px";

}

adapt(80);

</script>


<style>

div {
border: 1px solid black;
}

</style>

<div id = 'div'> </div>
6
  • 1
    Works for me jsfiddle.net/ozajqucz Commented Aug 11, 2015 at 2:49
  • it's working perfectly Commented Aug 11, 2015 at 2:49
  • Is your Javascript in the head section of the page? Commented Aug 11, 2015 at 2:50
  • Can you show us a fiddle? Where is your JavaScript located? Commented Aug 11, 2015 at 2:53
  • @Purag No. It's not in the head. Commented Aug 11, 2015 at 2:54

1 Answer 1

2

Your problem is that your Javascript appears before the element in the code. Browsers process HTML documents top-down, so your Javascript gets executed before there's even an element to act upon.

You can either put the function call inside a window.onload wrapper, or put the <script> tag after the div. Usually, it is placed at the end of the <body> tag since all elements will have been processed by the browser at that point.

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

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.