Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change div width live with jQuery

Tags:

jquery

css

width

Is it possible to change a div's width live with jQuery? And if it is, how?

What I want is to change its width depending on the browser's window width in real time, so if/when the user changes the browser window, the div's dimensions are changed as well in realtime.

like image 928
Alex Avatar asked Nov 16 '11 14:11

Alex


People also ask

How do I set the width of an element in jQuery?

jQuery width() Method The width() method sets or returns the width of the selected elements. When this method is used to return width, it returns the width of the FIRST matched element. When this method is used to set width, it sets the width of ALL matched elements.

What jQuery effect alters the width of an element?

The jQuery outerWidth() and outerHeight() methods get or set the outer width and the outer height of the element respectively. This outer width and height includes padding and border but excludes the margin on the element.

How do I set dynamic width?

Answer: Use the JavaScript width() method You can set the width of a <div> box dynamically using the jQuery width() method.


3 Answers

You can use, which will be triggered when the window resizes.

$( window ).bind("resize", function(){     // Change the width of the div     $("#yourdiv").width( 600 ); }); 

If you want a DIV width as percentage of the screen, just use CSS width : 80%;.

like image 144
Niels Avatar answered Sep 21 '22 23:09

Niels


It is indeed possible to change a div elements' width in jQuery:

$("#div").css("width", "300px"); 

However, what you're describing can be better and more effectively achieved in CSS by setting a width as a percentage:

#div {     width: 75%;     /* You can also specify min/max widths */     min-width: 300px;     max-width: 960px; } 

This div will then always be 75% the width of the screen, unless the screen width means the div will be smaller than 300px, or bigger than 960px.

like image 44
Rory McCrossan Avatar answered Sep 20 '22 23:09

Rory McCrossan


There are two ways to do this:

CSS: Use width as %, like 75%, so the width of the div will change automatically when user resizes the browser.

Javascipt: Use resize event

$(window).bind('resize', function()
{
    if($(window).width() > 500)
        $('#divID').css('width', '300px');
    else
        $('divID').css('width', '200px');
});

Hope this will help you :)

like image 44
Deviprasad Das Avatar answered Sep 18 '22 23:09

Deviprasad Das