2

Is there a way to get the realtime width and height values using Javascript and apply them to a number of div id's? I want to build a site that has 5 sections that are always width: 100vw and height: 100vh. Only one section can be seen at a time as each section has a # anchor and vertical scrolling is disabled.

The problem I'm having is when I resize the browser window, the CSS doesn't keep up and must be refreshed for new values for the section width and height. I'm wondering if there is a way for Javascript to constantly monitor the browser width and height and apply those values to a set of id's.

Example

The browser window is 1000px by 500px so the id #one, #two now have a width: 1000px and height: 500px and when the browser is resized to 1200px by 600px the values for #one , #two would be set as width: 1200px and height: 600px in the CSS.

Here is my codepen.

1
  • You should look into the resize event. In jQuery, $(window).on('resize', function () { /* recalculate sizes here */ }); Commented Aug 28, 2014 at 4:19

2 Answers 2

3

As @gary-storey already said, use the resize event:

$(window).resize(function() {
   var curWinWidth  = $(window).width();
   var curWinHeight = $(window).height();
   // do stuff here
});
Sign up to request clarification or add additional context in comments.

Comments

0

i've done this for my own page, that way:

$(window).resize(function() {
    <!-- get viewport size//set content size -->
    var currentViewPortHeight = $( window ).height();
    var currentViewPortWidth = $( window ).width(); 
    $("#mainFrame").css({ "height" : currentViewPortHeight, "width" : currentViewPortWidth });
    $("#mainFrame").resize();   
};

you may set a timeout interval though - since this event fires very often during a windo resize - especially if the user uses drag&drop. according to my stackoverflow studies, the best would be a 300ms timeout, to get a smooth resize transition, and not firing it to often...

1 Comment

of course - you have to change the #mainframe selector to match you own div id or class

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.