Fill box dynamically with screen height - javascript

I have a box, which I am trying to size perfectly to fit within the browser viewport if the image is not larger then it. So the image would appear to be centered within the window.
Currently I don' think my method of seeking the browser height is working. And for some reason there is a lot of extra space
Example (src)
here is where I define the page sizes
if ( style['img-width'] > screenwidth ) {
style['body-width'] = style['img-width'] + ( style['img-padding'] * 2 );
} else {
style['body-width'] = screenwidth;
}
style['body-height'] = ( style['img-height'] > screenheight ) ?
( style['img-height'] +
( style['img-padding'] * 2 ) +
style['header-height']
) :
screenheight;
$('body').css({ 'width': style['body-width']+'px' });
theater.css({
'width': style['body-width']+'px',
'height': style['body-height']+'px',
});
theaterheadcon.css('width', style['body-width']+'px');
theaterheader.css('width', style['body-width']+'px');
How I am defining screen width/height
screenwidth = isNaN(window.outerWidth) ? window.clientWidth : window.outerWidth,
screenheight = isNaN(window.outerHeight) ? window.clientHeight : window.outerHeight;

Here is the basic of centering items to a content with javascript and css:
/*css*/
#myImage
{
position:absolute;
}
And in java:
/*javascript*/
var img=$('#myImage');
var winWidth=$(window).width();
var winHeight=$(window).height();
if(img.height()>winHeight)
{
img.css('height', winHeight + "px");
}
img.css('left',(winWidth/2) + "px");
img.css('top',(winHeight/2) + "px");
img.css('margin-left',(-(img.width()/2)) + "px");
img.css('margin-top',(-(img.height()/2)) + "px");
The margin approach guaranties that the image will stay at the center even on page resize

I tried here in DIVs in your case code will detect your image size itself
$(document).ready(function(){
var windowheight = $(window).height();
var windowwidth = $(window).width();
var boxheight = $('#box').outerHeight();
var boxwidth = $('#box').outerWidth();
var imgheight = $('.img').outerHeight();
var imgwidth = $('.img').outerWidth();
if(imgheight > boxheight || imgwidth > boxwidth){
$('#box').css('height', windowheight).css('width', windowwidth);
$('.img').css('margin-left',((windowwidth - imgwidth)/2)+'px');
$('.img').css('margin-top',((windowheight - imgheight)/2)+'px');
}
});
DEMO
change your img width in css to see the action
if you want your div to not going outside the window after margin the image to center use that code
$(document).ready(function(){
var windowheight = $(window).height();
var windowwidth = $(window).width();
var boxheight = $('#box').outerHeight();
var boxwidth = $('#box').outerWidth();
var imgheight = $('.img').outerHeight();
var imgwidth = $('.img').outerWidth();
if(imgheight > boxheight || imgwidth > boxwidth){
$('#box').css('position','absolute').css('width', 'auto').css('height', 'auto').css('left', '0').css('top', '0').css('right', '0').css('bottom', '0');
$('.img').css('margin-left',((windowwidth - imgwidth)/2)+'px');
$('.img').css('margin-top',((windowheight - imgheight)/2)+'px');
}
});
DEMO

Related

Re-sizing Image Width Using JavaScript

I am trying to re-size an image in a popup. The original image is 6000 x 4000. I do a check to see if the image is greater than 500, and if so I just try and set the image to 500. Trying to set it using 'this', makes the pop open in a tab and the image is still its original size. If I try and set the image not using 'this', the pop up works as intended regarding where it is positioned on screen and the size of the box, but the image, is still its original size--6000 x 4000. (PS: I have to use ES5 as well.)
What gives?
Thanks,
CM
<script language="javascript" type="text/javascript"><!--
// let i=0;
function resize() {
console.log("Testing");
let i=0;
if (window.navigator.userAgent.indexOf('MSIE 6.0') != -1 && window.navigator.userAgent.indexOf('SV1') != -1) {
i=30; //This browser is Internet Explorer 6.x on Windows XP SP2
} else if (window.navigator.userAgent.indexOf('MSIE 6.0') != -1) {
i=0; //This browser is Internet Explorer 6.x
} else if (window.navigator.userAgent.indexOf('Firefox') != -1 && window.navigator.userAgent.indexOf("Windows") != -1) {
i=25; //This browser is Firefox on Windows
} else if (window.navigator.userAgent.indexOf('Mozilla') != -1 && window.navigator.userAgent.indexOf("Windows") != -1) {
i=45; //This browser is Mozilla on Windows
} else {
i=80; //This is all other browsers including Mozilla on Linux
}
var imgWidth = document.images[0].width;
var imgHeight = document.images[0].height;
console.log("Original image width is: " + imgWidth);
console.log("Original image height is: " + imgHeight);
if(imgWidth > 500){
//Shrink the image to size of popup frame
this.imgWidth = 500;
this.imgHeight = 500;
console.log("Adjusted image width is: " + imgWidth);
console.log("Adjusted image height is: " + imgHeight);
//Get display/screen width and height
var screenWidth = screen.width;
var screenHeight = screen.height;
console.log("Screen width is: " + screenWidth);
console.log("Screen height is: " + screenHeight);
//Set popup position on display/screen
var leftpos = screenWidth / 2 ;
var toppos = screenHeight / 2 - imgHeight / 2;
console.log("Left position is: " + leftpos);
console.log("Top position is: " + toppos);
//Set popup frame width and height equal to adjusted image width and height
var frameWidth = imgWidth;
var frameHeight = imgHeight+i;
console.log("Frame width is: " + frameWidth);
console.log("Frame height is: " + frameHeight);
window.moveTo(leftpos, toppos);
window.resizeTo(frameWidth,frameHeight+i);
}
else if (document.documentElement && document.documentElement.clientWidth) {
var imgHeight = document.images[0].height + 40 - i;
var imgWidth = document.images[0].width + 20;
var height = screen.height;
var width = screen.width;
var leftpos = width / 2 - imgWidth / 2;
var toppos = height / 2 - imgHeight / 2;
frameWidth = imgWidth;
frameHeight = imgHeight + i;
window.moveTo(leftpos, toppos);
window.resizeTo(frameWidth, frameHeight + i);
} else if (document.body) {
window.resizeTo(document.body.clientWidth, document.body.clientHeight - i);
}
self.focus();
}//end resize() function
//--></script>
Use
var imgWidth = document.images[0].style.width;
instead of
var imgWidth = document.images[0].width;

change height of div to browser window height so long a the browser height is greater than x

Hi I'm hoping someone will be able to explain what i am doing wrong here:
var winHeight = $(window).height(),
minHeight = 900,
Height = 900;
$(document).ready(function () {
if (winHeight < MinHeight) {
Height = minHeight;
} else {
Height = winHeight;
}
$('div.page').css('height', winHeight + 'px');
});
$(window).resize(function () {
if (winHeight < MinHeight) {
Height = minHeight;
} else {
Height = winHeight;
}
$('div.page').css('height', winHeight + 'px');
});
On my page I have multiple divs with the class "page".
I'm trying make the height of these the size of the browser window, unless the browser window is less than 900, then I want them to be 900px tall.
I'm guessing its a syntax issue. Especially since I'm brand new to jquery and javascript ( I only started using it today).
You have to call $(window).height() on the resize event, so you can respond to the current window size. You can go with this:
$(document).ready(function () {
//Call the method one time
updateWindowSize();
//Subscribe the method to future resize events
$(window).resize(updateWindowSize);
//updateWindowSize inside a closure to hide 'minHeight'
var updateWindowSize = (function(){
var minHeight = 900;
//Actual updateWindowSize function
return function(){
var winHeight = $(window).height();
var newHeight = winHeight < minHeight ? minHeight : winHeight;
$('div.page').height(newHeight);
}
})();
});
The problem is the value of winHeight is never changed when window resizes. And I wonder where the variable "Height" is used ?
The code should be:
$(document).ready(function () {
$(window).resize(function () {
var winHeight = $(window).height(),
minHeight = 900,
Height = 900;
if (winHeight < minHeight) {
Height = minHeight;
} else {
Height = winHeight;
}
$('div.page').height(Height);
});
});
Make sense?

How can I resize and crop/letterbox image to completely fill div with image whatever resize

This is what I need:
The image must completely fill 100% the area the div covers - left to
right and top to bottom.
the image must not be squashed or streched - just be cropped or
must overflow.
The image must be kept as small as possible, so whatever the resize - you
can still see either the very sides OR the very top and bottom.
The div itself will be adjusting in height and width as both are a percentage of the main window.
I have found a little bit of JavaScript here that is manipulating the image just how I want when the window is resized, but is displaying it in the whole window.
<html>
<head>
<title>test</title>
<script type="text/javascript">
function resizeImage()
{
var window_height = document.body.clientHeight
var window_width = document.body.clientWidth
var image_width = document.images[0].width
var image_height = document.images[0].height
var height_ratio = image_height / window_height
var width_ratio = image_width / window_width
if (height_ratio > width_ratio)
{
document.images[0].style.width = "100%"
document.images[0].style.height = "auto"
}
else
{
document.images[0].style.width = "auto"
document.images[0].style.height = "100%"
}
}
</script>
</head>
<body onresize="resizeImage()">
<img onload="resizeImage()" src="f/a.jpg">
</body>
</html>
Here is a demo
Please don't just answer that all I need is:
<img style="width : 100%;">
This is so much more than that.
It's not too easy to explain but check the demo and drag the corner of the window around and that'll be worth 1000 words...!
Can it (or something like it) be made to work the same way within a % sized div?
I wrote a jQuery plugin that does exactly this. Check out my blog post here and the demo here
jQuery.fn.resizeToParent = function(options) {
var defaults = {
parent: 'div'
}
var options = jQuery.extend(defaults, options);
return this.each(function() {
var o = options;
var obj = jQuery(this);
// bind to load of image
obj.load(function() {
// dimensions of the parent
var parentWidth = obj.parents(o.parent).width();
var parentHeight = obj.parents(o.parent).height();
// dimensions of the image
var imageWidth = obj.width();
var imageHeight = obj.height();
// step 1 - calculate the percentage difference between image width and container width
var diff = imageWidth / parentWidth;
// step 2 - if height divided by difference is smaller than container height, resize by height. otherwise resize by width
if ((imageHeight / diff) < parentHeight) {
obj.css({'width': 'auto', 'height': parentHeight});
// set image variables to new dimensions
imageWidth = imageWidth / (imageHeight / parentHeight);
imageHeight = parentHeight;
}
else {
obj.css({'height': 'auto', 'width': parentWidth});
// set image variables to new dimensions
imageWidth = parentWidth;
imageHeight = imageHeight / diff;
}
// step 3 - center image in container
var leftOffset = (imageWidth - parentWidth) / -2;
var topOffset = (imageHeight - parentHeight) / -2;
obj.css({'left': leftOffset, 'top': topOffset});
});
// force ie to run the load function if the image is cached
if (this.complete) {
obj.trigger('load');
}
});
}
And if you want the image to resize when the window is resized, just bind a resize handler to the window:
$(window).resize(function() {
$('img').resizeToParent();
});
Ok I've been playing around with it:
<html>
<head>
<title>test</title>
<style>
#imgarea {
position:absolute;
right:0px;
height:75%;
width:70%;
top:25%;
}
</style>
<script type="text/javascript">
function resizeImage()
{
var window_height = document.body.clientHeight
var window_width = document.body.clientWidth
var image_width = document.images[0].width
var image_height = document.images[0].height
var area_width = window_width * 0.7
var area_height = window_height * 0.75
var height_ratio = image_height / area_height
var width_ratio = image_width / area_width
if (height_ratio > width_ratio)
{
document.images[0].style.width = "100%"
document.images[0].style.height = "auto"
}
else
{
document.images[0].style.width = "auto"
document.images[0].style.height = "100%"
}
}
</script>
</head>
<body onresize="resizeImage()">
<div id="imgarea">
<img onload="resizeImage()" src="f/a.jpg">
</div>
</body>
</html>
It keeps resizing as the div resizes - as mentioned the div is
resizing with the window - this one keeps working seemlesly.
It seems to be OK across IE9, Fire Fox, Oprea, Chrome, and safari
over xp and 7
so really it answers my question perfectly, its just - now i've seen Christian's centering version i wish i had the know-how to make this do it i've tried a few things but am now stuck. Any Ideas?
P.S. if you dont know the width and height % of the div when you right the script i think it could be got with GetElementById - somehow... beyond me though;)

Mouse on left of screen move image to left, same when mouse on right of screen

I'm trying to get an image that is around 1920x1200px to pan around on a 800x600px browser window.
So if my mouse is on the top-left of the browser window the image is alined so it's top-left margins are on the top-left of the browser window. The same goes for the bottum-right.
So if the mouse is in the centre of the screen the image should be centered too.
Im not sure what calculations are needed as my math is a bit rusty.
Currently I'm using a bit of javascript that just moves the image using CSS's top/left properties but without much success as it's just moving the picture around from it's top/left corner.
I'v also set the image's position to absolute in css.
function updateImgPosition( e )
{
var avatar = document.getElementById("avatar");
// Width
var windowWidth = window.innerWidth;
var mouseWidthLocation = e.x;
var percentOfWidth = (100 / windowWidth) * mouseWidthLocation;
// Height
var windowHeight = window.innerHeight;
var mouseHeightLocation = e.y;
var percentOfHeight = (100 / windowHeight) * mouseHeightLocation;
avatar.style.top = percentOfHeight + "%";
avatar.style.left = percentOfWidth + "%";
}
document.onmousemove = updateImgPosition;
This is a demo of what I have: http://jsfiddle.net/uQAmQ/1/
Fiddle: http://jsfiddle.net/uQAmQ/2/
You should not "pan" on an absolutely positioned element, because the window's width and height keep changing according to the image. A smoother solution involves using a background image. See the middle of my answer for the used logic.
Consider this JavaScript (read comments; HTML + CSS at fiddle):
(function(){ //Anonymous function wrapper for private variables
/* Static variables: Get the true width and height of the image*/
var avatar = document.getElementById("avatar");
var avatarWidth = avatar.width;
var avatarHeight = avatar.height;
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
/* Logic: Move */
var ratioY = (avatarHeight - windowHeight) / windowHeight;
var ratioX = (avatarWidth - windowWidth) / windowWidth;
function updateImgPosition( e ) {
var mouseY = e.pageX; //e.pageX, NOT e.x
var mouseX = e.pageY;
var imgTop = ratioY*(-mouseY);
var imgLeft = ratioX*(-mouseX);
document.body.style.backgroundPosition = imgLeft + "px " + imgTop + "px";
}
/* Add event to WINDOW, NOT "document"! */
window.onmousemove = updateImgPosition;
})();
The logic behind it:
Relative units cannot be used, because the image size is specified in absolute units.
The offsets should change according to a specific ratio, which is similar to: image size divided by window size.However, this ratio is not complete: The image would disappear at the bottom/left corner of the window. To fix this, substract the window's size from the image's size. The result can be found in the code at variable ratioX and ratioY.
The previous code had to be loaded at the window.onload event, because the image's size was dynamically calculated. For this reason, a HTML element was also included in the body.
The same code can be written much smaller and efficient, by specifying the size of the background in the code. See this improved code. Fiddle: http://jsfiddle.net/uQAmQ/3/
(function(){ //Anonymous function wrapper for private variables
/* Static variables: Get the true width and height of the image*/
var avatarWidth = 1690;
var avatarHeight = 1069;
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
/* Logic: Move */
var ratioY = (avatarHeight - windowHeight) / windowHeight;
var ratioX = (avatarWidth - windowWidth) / windowWidth;
function updateImgPosition( e ) {
var mouseX = e.pageX; //e.pageX, NOT e.x
var mouseY = e.pageY;
var imgTop = ratioY*(-mouseY);
var imgLeft = ratioX*(-mouseX);
document.body.style.backgroundPosition = imgLeft + "px " + imgTop + "px";
}
/* Add event to WINDOW, NOT "document"! */
window.onmousemove = updateImgPosition;
})();
If you don't mind a decreased code readability, the following code is the best solution, Fiddle: http://jsfiddle.net/uQAmQ/4/:
(function(){ //Anonymous function wrapper for private variables
/* Static variables: Get the true width and height of the image*/
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
var ratioY = (windowHeight - 1069) / windowHeight;
var ratioX = (windowWidth - 1690) / windowWidth;
window.onmousemove = function( e ) {
document.body.style.backgroundPosition = ratioX * e.pageX + "px " + ratioY * e.pageY + "px";
}
})();

"Zooming" elements on a page while keeping the centre of enlargement in the centre of the window

I'm trying to work out how to enlarge all elements on a page, but keep the centre of enlargement in the centre of the window.
On this page, once the image reaches the top or the left side of the window the centre of enlargement changes. It also changes when you move the image. (exactly what you would expect)
I'm thinking I'd need to take a completely different approach to achieve what I want. But I'm not sure what that approach is..
Any ideas?
Well, here's my take.
Only thing is that I ditched the containers you were using. Is that cheating? Seems like they were only there to get the image centered. No need.
This works as expected with no side effects.
Here's a working demo you can test:
http://jsfiddle.net/YFPRB/1/
(You need to click on the pane with the baboon first.)
HTML
<body>
<img src="http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png" />
</body>
CSS
html, body {
width: 100%;
height: 100%;
overflow: hidden;
}​
jQuery
EDIT: Thanks to #stagas for the reminder to clean up redundancies.
var $img = $('img'); // Cache the image. Better for performance.
$img.draggable();
$img.css({left: ($('body').width() / 2) - ($img.width() / 2)})
.css({top: ($('body').height() / 2) - ($img.height() / 2)})
$(document).keydown(function(event) {
if (event.keyCode == 38) {
var adjustment = 1.25;
} else if (event.keyCode == 40) {
var adjustment = 0.8;
} else {
return;
}
var offset = $img.offset();
var width = $img.width();
var height = $img.height();
var newWidth = width * adjustment;
var newHeight = height * adjustment;
var diffWidth = newWidth - width;
var diffHeight = newHeight - height;
var hcenter = $('body').width() / 2;
var vcenter = $('body').height() / 2;
var leftPercent = (hcenter - offset.left) / width;
var topPercent = (vcenter - offset.top) / height;
$img.offset({top: offset.top - (diffHeight * topPercent), left: offset.left - (diffWidth * leftPercent)});
$img.width(newWidth).height(newHeight);
});​
This is what I came up, it works as you say except the image will always go to the center after zooming in or out:
$('document').ready(function() {
zoomimg=$('#zoomimg'); // we store this in a variable since we don't need to traverse the DOM every time -- this is faster
var viewportWidth = $(window).width();
var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height(); // this is to work with Opera
zoomimg.css({'position': 'absolute', 'left': (viewportWidth/2)-(zoomimg.width()/2), 'top' : (viewportHeight/2)-(zoomimg.height()/2)}).draggable();
$(document).keydown(function(event) {
event = event || window.event;
var viewportWidth = $(window).width();
var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height(); // this is to work with Opera
if (event.keyCode == 38) {
width = zoomimg.width();
height = zoomimg.height();
zoomimg.width(width*1.2).height(height*1.2);
var viewportWidth = $(window).width();
var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height();
zoomimg.css({'left': (viewportWidth/2)-(zoomimg.width()/2), 'top' : (viewportHeight/2)-(zoomimg.height()/2)});
} else if (event.keyCode == 40) {
width = zoomimg.width();
height = zoomimg.height();
zoomimg.width(width*0.8).height(height*0.8);
var viewportWidth = $(window).width();
var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height();
zoomimg.css({'left': (viewportWidth/2)-(zoomimg.width()/2), 'top' : (viewportHeight/2)-(zoomimg.height()/2)});
} else {
return
}
});
});
You should put an ID 'zoomimg' on the tag for it to work, and overflow:hidden on the #container . Also ditch that display:table and display:table-cell they're useless now that we center with Javascript. Also, pressing the down arrow key will cause the container to scroll down, so you should use other keys, as the arrows are reserved by the browser for scrolling the viewport.

Categories

Resources