I’m creating a plugin to help make sites responsive. The first step is to create a failsafe so things still look as they’re supposed to.
On page load, I want to get the elements’ width at maximum window size. At present, I just do this:
var theElements = ['div',
'section',
'table',
'article',
'aside',
'details',
'figcaption',
'figure',
'footer',
'header',
'hgroup',
'nav',
'section',
'summary'];
for (var i=0; i<theElements.length; i++){
$(theElements[i]).each(function(){
var theWidth = $(this).width();
$(this).css('max-width', theWidth + "px");
});
}
This works pretty well, but it only gets the element’s width at the window size on page load – so if the window is only 500px, that’s the container size I’m stuck with.
What I’d like to do
In simplest terms, I’m trying to get what the page is meant to look like, how it was designed to look. There’s no way of knowing whether the site’s designer has used margins, concrete pixel values or percentages to code their site, so the simplest way is to just make the window large enough to say “Yep, that’s how it’s meant to look”.
I’d like to be able to either very quickly set the window width to, say, 1280px, calculate theElements widths then set it back to whatever it was (this is not a good option as it’s obtrusive for the user) or otherwise find some way to calculate what the elements’ width would be IF the body width were 1280px (much better UX but not sure if it’s possible).
What’s the best way to achieve this?
You could set the body‘s width (or, barring that, the
<html>element’s) to 1280, calculate all your widths, and then change it back to auto. As long as JS is running with no interruption, the browser won’t redraw anything.The only other option I can see is to clone the entire document into a hidden element with a fixed width, then throw it all away. That’s quite a bit more expensive, though.