Resizing a div and background with javascript - javascript

I'm trying to change the height of my header div and its background based on the height of the screen.
Here is what I have so far:
function getScreenSize() {
"use strict";
var h = window.innerHeight;
document.getElementById("header").style.height = h;
}
and then I used onload with the body tag.
<body onload="getScreenSize()">
Here's the full site on js fiddle just in case.
thanks for your help.

You need to specify units when setting styles with JavaScript:
document.getElementById("header").style.height = h + 'px'; //added + 'px'

Related

Foundation 6: How to set .is-open-right translateX value with JavaScript

I am building a website with Foundation 6 using CSS instead of SCSS. I'm using the responsive off-canvas drill-down menu on small screens, and by default, the off-canvas menu width is 250px.
Problem: I would like this to be the full width of the browser window instead.
Setting the Width
I have used JavaScript to dynamically set the .off-canvas.position-right width to the width of the window, and right to the negative width of the window. I've also set the .off-canvas .drilldown max-width to the width of the window.
This works well, and here's how I did it:
function setOffCanvasWidth() {
var windowWidth = window.innerWidth,
offCanvasRight = document.querySelector( '.off-canvas.position-right' ),
isDrilldown = document.querySelector( '.off-canvas .is-drilldown' );
offCanvasRight.style.width = windowWidth + "px";
offCanvasRight.style.right = "-" + windowWidth + "px";
isDrilldown.style.maxWidth = windowWidth + "px";
}
setOffCanvasWidth();
I'm happy with this part, but it only solves half of the problem.
Moving the Off-Canvas
In addition to dealing with the width of the menu, .is-open-right is moving everything over by -250px using transform: translateX().
I tried including these lines in my function to set the transform: translateX() value to the negative width of the window:
var offCanvasWrapperInner = document.querySelector( '.off-canvas-wrapper-inner.is-off-canvas-open.is-open-right' );
offCanvasWrapperInner.style.transform = "translateX(-" + windowWidth + "px)";
But this didn't work. I think it has to do with the fact that .off-canvas-wrapper-inner doesn't have the class .is-open-right when the window loads. That class is added dynamically after clicking the hamburger toggle button, which has a class of .menu-icon. So I tried adding a click event listener, but it still doesn't work.
Here is my JS code in its entirety:
function setOffCanvasWidth() {
var windowWidth = window.innerWidth,
offCanvasRight = document.querySelector( '.off-canvas.position-right' ),
isDrilldown = document.querySelector( '.off-canvas .is-drilldown' ),
menuIcon = docuemnt.querySelector( '.menu-icon' ),
offCanvasWrapperInner = document.querySelector( '.off-canvas-wrapper-inner.is-off-canvas-open.is-open-right' );
offCanvasRight.style.width = windowWidth + "px";
offCanvasRight.style.right = "-" + windowWidth + "px";
isDrilldown.style.maxWidth = windowWidth + "px";
menuIcon.addEventListener( 'click', function() {
offCanvasWrapperInner.style.transform = "translateX(-" + windowWidth + "px)";
} );
}
setOffCanvasWidth();
Where Am I Going Wrong?
I'm not looking for anyone to code the solution for me, necessarily, but any feedback and direction on how I might set the .is-open-right translateX value would be very helpful.
Here is the entire project code: https://github.com/paulshryock/paulshryock/releases/tag/v0.0.1
Here is a live demo: https://paulshryock.github.io/paulshryock/
Use a translateX value of -100%. Percentage transformations are based on the element's dimensions, so 100% would be equal the element's width. At this point no JavaScript would be needed.
On that note, I would recommend setting the menu's left to 100% instead of setting right to the negative width.

Get constant browser height and width

I was wondering how I could constantly get the current browser's height and width. Right now, I am using jQuery and have something like this:
var height = window.innerHeight;
var width = window.innerWidth;
This does initially work as it gets the screen when the page is loaded up. However, when the user changes the screen width/height manually, I can't seem to get the current dimensions and the page starts faulting with errors. How should I be checking the dimensions at all times? I've tried googling the answer but I can't seem to find anything applicable, though I'm sure many others have had the same issue (I don't think I'm searching up the right keywords!). Please let me know what I can do!! Thanks!
Use a window.onresize function as well as a window.onload handler to update the width and height variables.
(Resizeable Demo)
var width,height;
window.onresize = window.onload = function() {
width = this.innerWidth;
height = this.innerHeight;
document.body.innerHTML = width + 'x' + height; // For demo purposes
}
Using jQuery objects it would look like this.
(Resizeable Demo)
var width,height;
$(window).on('load resize', function() {
width = this.innerWidth; // `this` points to the DOM object, not the jQuery object
height = this.innerHeight;
document.body.innerHTML = width + 'x' + height; // For demo purposes
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Try this:
$(window).on("resize",function(){
console.log($(this).height() + " " + $(this).width());
});
fiddle
Try this
var width = window.outerWidth;
var height = window.outerHeight;
To resize the current window, use
window.resizeTo(width, height);
You can trigger the resize function using:
$( window ).resize(function() {
//....
});
Hope it helps you
You can use this to detect a change in screen size:
$(window).resize(function() {
height = window.innerHeight;
width = window.innerWidth;
//other code you wish to run on screen size change;
});
This assumes that height and width were declared in a scope that the function has access to. Otherwise make sure to place var before each variable.

Proportionally scale website to fit browser window

What would be an elegant solution to proportionally scale and center an entire website to fit a browser window (and updating as it's re-sized)
Assume the base layout is 720x500px
Content should proportionally scale to fit, and then re-center.
Essentially, operating like this Flash plugin: http://site-old.greensock.com/autofitarea/ (though base size is known)
Site will contain several different types of elements in that 720x500 area... ideal solution would just scale the whole thing, not needing to style each individual element (in case it matters- images will be SVG and so scaling should have no negative affect on resolution)
Depending on the browsers you need to support (IE9+), you could achieve that with simple CSS transform.
See an example (using jQuery) in this jsfiddle
var $win = $(window);
var $lay = $('#layout');
var baseSize = {
w: 720,
h: 500
}
function updateScale() {
var ww = $win.width();
var wh = $win.height();
var newScale = 1;
// compare ratios
if(ww/wh < baseSize.w/baseSize.h) { // tall ratio
newScale = ww / baseSize.w;
} else { // wide ratio
newScale = wh / baseSize.h;
}
$lay.css('transform', 'scale(' + newScale + ',' + newScale + ')');
console.log(newScale);
}
$(window).resize(updateScale);
If you need backwards compatibility, you could size everything in your site with % or em, and use a similar javascript to control the scale. I think that would be very laborious though.
One solution I'm using is working with a container in which I put an iframe that's being resized to fit as much available screen as possible without losing it's ratio. It works well but it's not completely flexible: you need to set dimensions in your content page in % if you want it to work. But if you can manage your page this way, I think it does pretty much what you want.
It goes like this. You create a container html page that's basically only styles, the resize script and the iframe call. And you content goes into the iframe page.
<style>
html, body
{
border: 0px;margin: 0px;
padding:0px;
}
iframe
{
display: block;
border: 0px;
margin: 0px auto;
padding:0px;
}
</style>
<script>
$(document).ready(function(e){
onResizeFn();
});
$(window).resize(function(e){
onResizeFn();
});
// this stretches the content iframe always either to max height or max width
function onResizeFn(){
var screen_ratio = 0.70 // this is your 720x500 ratio
if((window.innerHeight/window.innerWidth) > screen_ratio){
var theWidth = window.innerWidth
var theHeight = (window.innerWidth*screen_ratio);
} else {
var theHeight = window.innerHeight;
var theWidth = (window.innerHeight/screen_ratio);
}
document.getElementById("your_iframe").width = theWidth + "px"
document.getElementById("your_iframe").height = theHeight + "px"
}
</script>
// And then you call your page here
<iframe id='your_iframe' src='your_content_page' scrolling='no' frameborder='0'"></iframe>

Resize iframe to content with Jquery

I'm trying to resize an iframe dynamicly to fit its content. To do so I have a piece of code:
$("#IframeId").height($("#IframeId").contents().find("html").height());​
It doesnt work. Is it because of cross-domain issue? How do I get it to fit? Please take a look at Fiddle: JsFiddle
ps I have set the html and body of the link height:100%;
You just need to apply your code on the iframe load event, so the height is already known at that time, code follows:
$("#IframeId").load(function() {
$(this).height( $(this).contents().find("body").height() );
});
See working demo . This demo works on jsfiddle as I've set the iframe url to a url in the same domain as the jsfiddle result iframe, that is, the fiddle.jshell.net domain.
UPDATE:
#Youss:
It seems your page for a strange reason don't get the body height right, so try using the height of the main elements instead, like this:
$(document).ready(function() {
$("#IframeId").load(function() {
var h = $(this).contents().find("ul.jq-text").height();
h += $(this).contents().find("#form1").height();
$(this).height( h );
});
});
Not sure why #Nelson's solution wasn't working in Firefox 26 (Ubuntu), but the following Javascript-jQuery solution seems to work in Chromium and Firefox.
/**
* Called to resize a given iframe.
*
* #param frame The iframe to resize.
*/
function resize( frame ) {
var b = frame.contentWindow.document.body || frame.contentDocument.body,
cHeight = $(b).height();
if( frame.oHeight !== cHeight ) {
$(frame).height( 0 );
frame.style.height = 0;
$(frame).height( cHeight );
frame.style.height = cHeight + "px";
frame.oHeight = cHeight;
}
// Call again to check whether the content height has changed.
setTimeout( function() { resize( frame ); }, 250 );
}
/**
* Resizes all the iframe objects on the current page. This is called when
* the page is loaded. For some reason using jQuery to trigger on loading
* the iframe does not work in Firefox 26.
*/
window.onload = function() {
var frame,
frames = document.getElementsByTagName( 'iframe' ),
i = frames.length - 1;
while( i >= 0 ) {
frame = frames[i];
frame.onload = resize( frame );
i -= 1;
}
};
This continually resizes all iframes on a given page.
Tested with jQuery 1.10.2.
Using $('iframe').on( 'load', ... would only work intermittently. Note that the size must initially be set to 0 pixels in height if it is to shrink below the default iframe height in some browsers.
What you can do is the following:
Within the iFrame use document.parent.setHeight(myheight) to set the height within the iFrame to the parent. Which is allowed since it is a child control. Call a function from the parent.
Within the parent you make a function setHeight(iframeheight) which resizes the iFrame.
Also see:
How do I implement Cross Domain URL Access from an Iframe using Javascript?
Just do it on the HTML tag, works perfect
$("#iframe").load(function() {
$(this).height( $(this).contents().find("html").height() );
});
As the answer to the question use an already outdated jquery (load has been deprecated and replaced with .on('load',function(){}), below is the latest code for the answer in the question.
Note that I use the scrollHeight and scrollWidth, which I think will load much nicer than using Height and Width like the answer provided. It will totally fit, without scroll anymore.
$("#dreport_frame").on('load',function(){
var h = $('#dreport_frame').contents().find("body").prop('scrollHeight');
var w = $('#dreport_frame').contents().find("body").prop('scrollWidth');
$('#dreport_frame').height(h);
$('#dreport_frame').width(w);
})
Adjust height of an iframe, on load and resize, based on its body height.
var iFrameID = document.getElementById('iframe2');
var iframeWin = iFrameID.contentWindow;
var eventList = ["load", "resize"];
for(event of eventList) {
iframeWin.addEventListener(event, function(){
if(iFrameID) {
var h = iframeWin.document.body.offsetHeight + "px";
if(iFrameID.height == h) {
return false;
}
iFrameID.height = "";
iFrameID.height = iframeWin.document.body.offsetHeight + "px";
}
})
}
At end, I come with this cross-domain solution that work also for resize...
(resize not triggering : Auto resize iframe height when the height of the iframe contents change (same domain) )
Iframe :
(function() {
"use strict";
var oldIframeHeight = 0,
currentHeight = 0;
function doSize() {
currentHeight = document.body.offsetHeight || document.body.scrollHeight;
if (currentHeight !== oldIframeHeight) {
console.log('currentHeight', currentHeight);
window.parent.postMessage({height:currentHeight}, "*");
oldIframeHeight = currentHeight;
}
}
if (window.parent) {
//window.addEventListener('load', doSize);
//window.addEventListener('resize', doSize);
window.setInterval(doSize, 100); // Dispatch resize ! without bug
}
})();
Parent page :
window.addEventListener('message', event => {
if (event.origin.startsWith('https://mysite.fr') && event.data && event.data.height) {
console.log('event.data.height', event.data.height);
jQuery('#frameId').height(event.data.height + 12);
}
});

Continuously check page (client) height and change footer height according to that value

At my website, I try to accomplish (with javascript) that the footer height changes if the page height is larger then a specific value (907 pixels, the body height). It also needs to change if the page height changes (so if the viewer changes his client height).
I use jQuery to get the page height, but I need it's continuously checked, and not only when the page loads.
This is the snippet I use:
$(document).ready(function(){
var windowheight = $(window).height();
if(windowheight >= "907") {
var extrafooterheight = windowheight - 907;
$('#footer').height(40 + extrafooterheight);
$('body').height(907 + extrafooterheight);
}
});
Thanks for your help.
I suggest attaching to the resize event of the window using jQuery:
$(document).ready(function(){
$(window).resize(function() {
var windowheight = $(window).height();
if(windowheight >= "907") {
var extrafooterheight = windowheight - 907;
$('#footer').height(40 + extrafooterheight);
$('body').height(907 + extrafooterheight);
}
});
});
Take a look at the jQuery resize() docs.

Categories

Resources