Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQUERY: Resize div to window width

Tags:

jquery

I am trying to force the width of a div to the width of a browser window. So that even if the window is resize the adjusts it's width.

I have been researching for about an hour and have found odd bits and pieces such as .resize() but can't find anything which works.

like image 963
Guy Avatar asked Nov 11 '11 14:11

Guy


People also ask

How do you trigger a resize event?

In your modern browsers, you can trigger the event using: window. dispatchEvent(new Event('resize'));

What happens when window is resized?

The resize event fires when the document view (window) has been resized. This event is not cancelable and does not bubble. In some earlier browsers it was possible to register resize event handlers on any HTML element.


2 Answers

Without a container limiting the width, a div should span the width of the browser window by default. You can explicitly set the width to 100%, but that shouldn't be necessary:

<div style="width:100%;">Hello world</div>

I think CSS is more appropriate here, but you can do this in jQuery like this:

$("#div1").width($(window).width());

To run the above code whenever the window is resized, you can do this:

$(window).resize(function(){
    $("#div1").width($(window).width());
});

Here's a jsFiddle. For the sake of demonstration, the div expands on button click.

like image 52
James Johnson Avatar answered Oct 14 '22 12:10

James Johnson


Try this:

<div id="full"></div>

<script type="text/javascript">
    function reSize($target){
        $target.css('width', $(window).width()+'px');
    }
    $(document).ready(function(){
        $(window).bind('resize', reSize($('#full')));
        $(window).trigger('resize');
    });
</script>

I hope this helps!

like image 1
dSquared Avatar answered Oct 14 '22 12:10

dSquared