misagh01
misagh01

Reputation: 11

How to Change a div width when size of browser window change with javascript

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?

Upvotes: 0

Views: 1483

Answers (3)

Nillervision
Nillervision

Reputation: 441

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>

Upvotes: 0

Dean Meehan
Dean Meehan

Reputation: 2647

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;
});

Upvotes: 2

SSMA
SSMA

Reputation: 497

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

Upvotes: 2

Related Questions