1

Here's a simple webpage. Why doesn't the textarea's width change when the browser is resized?

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
    function resize() {
        document.getElementById("main").style.width=window.innerWidth;
    }
    window.onresize = resize;
    window.onload = resize;
</script>
</head>
<body style="margin:0; padding:0;">
<textarea id="main" style="margin:0; padding:0; border:0;" >It was a dark and stormy night, and the rain came pouring down... </textarea>
</body>
</html>
4
  • 3
    @Phil The OP is running it onload...How is it not there? If only we could downvote comments. Commented Dec 11, 2013 at 2:20
  • @epascarello oops. Skim reading questions is not advised :) Commented Dec 11, 2013 at 2:22
  • Thanks to everyone who chimed in with the right answer. I'm a little rusty with this stuff. Commented Dec 11, 2013 at 2:28
  • @Phil I'd been trying to for the past 7 minutes... :) Commented Dec 11, 2013 at 2:34

3 Answers 3

2

The style.width requires a unit to be set, like px.

document.getElementById("main").style.width=window.innerWidth + "px";
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

<!DOCTYPE html>
<html>
<head>
</head>
<body style="margin:0; padding:0;">
<textarea id="main" style="margin:0; padding:0; border:0;" >It was a dark and stormy night, and the rain came pouring down... </textarea>
<script type="text/javascript">
    function resize() {
        document.getElementById("main").style.width=window.innerWidth + 'px';
    }
    window.onresize = resize;
    window.onload = resize;
</script>
</body>
</html>

5 Comments

How would this fix the problem?
Ok, I retracted my downvote, but why move the script below the textarea? As stated in the comments under the question, it's running at window.onload and window.onresize. The element exists when the function executes. True, this won't hurt anything, but there should be a reason for suggesting to do this.
@Travesty3 This is my habit when I use javascript to make sure my code will always run even if not 'onload'. I think it's good to change.
I think instead of just adding a block of code as your answer, it would be helpful to include why it solves the problem
Sorry about that. But I'm not really good at English. I'm Vietnamese :D. I will try so hard, thanks for remind.
1

Replace your line to this:

document.getElementById("main").style.width=window.innerWidth + 'px';

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.