0

How to Change a div width when size of browser window change with javascript (no jQuery)? I want to perform this job dynamically when user resize his browser. Please help, Immediately ... any suggestion for this job with css?

4
  • 2
    why not only with css? Commented Mar 25, 2014 at 14:47
  • Have you read up on the resize event? What have you tried so far? developer.mozilla.org/en-US/docs/Web/Reference/Events/resize Commented Mar 25, 2014 at 14:47
  • You should use CSS for as simple a task as this because under heavy load, CSS performs much better jQuery. Commented Mar 25, 2014 at 14:49
  • 2
    Why would you do this via Javascript? use CSS. You can do something like div { width: 80%; } that will resize depending of the size of the window, keeping the div at 80% of the window. If not that you can look into Media Queries Commented Mar 25, 2014 at 14:50

3 Answers 3

2

Use percentage. for example width="50%" This will change the width when browser size change.

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

1 Comment

this code doesn't work for me because the parent of div element has fixed width and shoulde has a fixed width.
2

You can either set this with CSS or Javscript

CSS would be easily done using %'s ie

div {
    width: 95%;
}

JS would be easily done using

var element = document.getElementById("x");
window.addEventListener('resize', function(event) {
    element.style.width = window.style.width;
});

1 Comment

What exactly doesnt work? jsfiddle would be great to help you out
0

This code should work in all browsers. But you really should use CSS instead.

<!DOCTYPE html >
<html>
<head>
    <meta charset="utf8" />
    <title>untitled</title>
</head>
<body>
<div id="myDiv" style=" height: 200px; margin:10px auto; background: green;"></div>

<script type="text/javascript">
var myElement = document.getElementById('myDiv');
function detectWidth(){
    var myWidth = 0;
    if(typeof (window.innerWidth)== 'number'){
        myWidth = window.innerWidth; 
    }
    else {
        myWidth = document.documentElement.clientWidth;  //IE7
    }
    myElement.style.width=myWidth-300+'px';
}
window.onload=function(){
    detectWidth();  
};
window.onresize = function (){
    detectWidth();
};
</script>
</body>
</html>

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.