Keep aspect ratio of div when resizing window - javascript

I have an issue which is a little hard to explain. I have a div which has a 2:1 aspect ratio. And I want it to have a 100% width or height based on the browsers window size.
If the window height is greater than the divs height the the size should be based on 100% width.
And if window height is less than the divs height the size should be based on 100% height.
With my curren approach it is flashing when I size larger.
Look at this link http://acozmo.com/me/ for a demo.
HTML
<section id="container">
</section>
JQuery
function update() {
var $documentHeight = $(document).height();
var $windowHeight = $(window).height();
var $documentWidth = $(document).width();
var $windowWidth = $(window).width();
var $container = $('#container');
if ( $windowHeight >= $documentHeight ) {
$container.width($windowWidth);
$container.height($windowWidth / 2);
}
if ( $windowHeight < $documentHeight ) {
$container.width($windowHeight * 2);
$container.height($windowHeight);
}
}
$(document).ready(function() {
update()
});
$(window).resize(function() {
update();
})

To resize to fit inside the window while maintaining aspect ratio, set up your container with an initial size and then divide the area width by the container's width to get the scale. You then need a check to make sure that scale doesn't make the height too great. See code below and fiddle - I've added the case where the height is greater than the width too for completeness.
To stop the flashing, throttle your resize function using setTimeout. This will ensure that update is only called once every n milliseconds. You can play with the number until you find the right balance.
var container = $('#container'),
updateTimeout,
threshold = 100;
function update() {
var windowWidth = $(window).width(),
windowHeight = $(window).height(),
width = container.width(),
height = container.height(),
scale;
if ( windowWidth > windowHeight ) {
scale = windowWidth / width;
if ( height * scale > windowHeight ) {
scale = windowHeight / height;
}
}
else {
scale = windowHeight / height;
if ( width * scale > windowWidth ) {
scale = windowWidth / width;
}
}
container.width(Math.round(width * scale));
container.height(Math.round(height * scale));
}
$(document).ready(function() {
update();
});
$(window).resize(function() {
clearTimeout(updateTimeout);
updateTimeout = setTimeout(update, threshold);
});

It's probably happening because the fact that you are using a second if, instead of an else . . . it hits the first if, shrinks the height, and then hits the second if and increases it.
Try changing this (the second if):
if ( $windowHeight < $documentHeight ) {
. . . to this:
else {

Related

How to make the slide take 100% versus re-sizing according to browser?

I have a fullscreen slideshow page, but the slides don't take up 100% of the background. Instead, they base size off of the browser. I want the slides to take 100% of the background. I THINK I narrowed it down to one function, but I'm not sure and not good with JavaScript yet. Here's the function:
// calculate image size, top and left position
jQuery.fn.superbgCalcSize = function(imgw, imgh) {
var options = $.extend($.fn.superbgimage.defaults, $.fn.superbgimage.options);
// get browser dimensions
var browserwidth = $(window).width();
var browserheight = $(window).height();
// use container dimensions when inlinemode is on
if (options.inlineMode === 1) {
browserwidth = $('#' + options.id).width();
browserheight = $('#' + options.id).height();
}
// calculate ratio
var ratio = imgh / imgw;
// calculate new size
var newheight = 0; var newwidth = 0;
if ((browserheight / browserwidth) > ratio) {
newheight = browserheight;
newwidth = Math.round(browserheight / ratio);
} else {
newheight = Math.round(browserwidth * ratio);
newwidth = browserwidth;
}
// calculate new left and top position
var newleft = Math.round((browserwidth - newwidth) / 2);
var newtop = Math.round((browserheight - newheight) / 2);
var rcarr = [newwidth, newheight, newleft, newtop];
return rcarr;
};
Let me know if there needs to be more code or even to link to the entire document, as I said I'm not at all experienced with JS and don't know where the problem resides.
*I've tried doing it with CSS, but I get a bug where as it's transitioning to the next image it bleeps the first image's actual size just before displaying the next and it's rather unsleek. Fixing this would also solve my question.

JavaScript window resize with proportions

I open a window with w=window.open('','', 'width=1000,height=700'); than i want this window to be resized with proportion 10/7.
for example: 500/350; 100/70 ...
i've maximum and minimum sizes already:
var w;
function openwindow()
{
w=window.open('','', 'width=1000,height=700');
w.focus();
resize(w);
}
function resize(w_obj) {
w_obj.onresize = function(event) {
width = w_obj.innerWidth;
height = w_obj.innerHeight;
// if popup width is greather then 1000px
if (width > 1000) {
w_obj.resizeTo(1000,700);
}
// if popup height is greather then 700px
if(height >700) {
w_obj.resizeTo(1000,700);
}
if (width < 500) {
w_obj.resizeTo(500,350);
}
if(height < 350) {
w_obj.resizeTo(500,350);
}
}
}
You should use outerHeight as that's what resizeTo's arguments mean. A problem however is that you cannot know whether the user resizes the width or the height of the window. Thus, you do not know what dimension to use as the reference and which to calculate.
Anyway, what you want is the following:
Clamp width and height between its minimum and maximum size. You can use Math.min/Math.max for this.
Set height to width multiplied by the 7 / 10 ratio.
See http://jsfiddle.net/bSE9C/1/.
var width = w_obj.outerWidth;
var height = w_obj.outerHeight;
width = Math.min(width, 1000); // may not exceed 1000 maximum
height = Math.min(height, 700);
width = Math.max(width, 500); // may not exceed 500 minimum
height = Math.max(height, 350);
height = width * 7 / 10;
w_obj.resizeTo(width, height);

Resizable / fluid images wrapped in a div?

im trying to get some images to resize automatically when a window resizes.
I have this working with the code below, however I would like to have a little more control over the image such as being able to set a min-height, any ideas??
also maybe wrap the images in a div so there is a little more control? Im not to good with js so any help or explanations would help
$(function() {
var $img = $(".l");
var ratio;
var offsetX = $img.offset().left;
var offsetY = $img.offset().top;
$(window).load(function () {
ratio = $img.width() / $img.height();
$(this).resize();
});
$(window).resize(function () {
var viewportWidth = window.innerWidth || document.documentElement.clientWidth;
var viewportHeight = window.innerHeight || document.documentElement.clientHeight;
var availWidth = viewportWidth - offsetX - 70;
var availHeight = viewportHeight - offsetY - 70;
if (availWidth / availHeight > ratio) {
$img.height(availHeight);
$img.width(availHeight * ratio);
}
else {
$img.width(availWidth);
$img.height(availWidth / ratio);
}
});
});
Just use CSS:
img { width: 100%; }
You can then apply height or min-height as you need.
To see it working, resize the window of this fiddle:
Example fiddle

How to fix the width and height of jquery lightbox?

I have aplied jquery lighbox on my image gallery, but due to the variable size of images, the lightbox size is not fixed hence opens up with image's original size, this in turn causes the biga images to go out of screen and display horizontal scroll bar in browser.
Hence I am looking for the way to apply the fix width and height to lightbox so that every image must be displayed with this size in lightbox.
Please help..
Update
i Just tried with the solution Scott (http://geekswithblogs.net/wojan/archive/2009/06/17/jquerylightbox.aspx) has given to me, I did this,
function _resize_container_image_box(intImageWidth,intImageHeight) {
// Get current width and height
//rescale if necessary
if((settings.maxWidth != null && settings.maxHeight != null) && (intImageWidth > settings.maxWidth || intImageHeight > settings.maxHeight)){
var isWider = intImageWidth > intImageHeight;//is the image wide or tall?
var scale = isWider ? settings.maxWidth/intImageWidth : settings.maxHeight/intImageHeight;
intImageWidth = intImageWidth * scale;
intImageHeight = intImageHeight * scale;
}
$('#lightbox-image').height(intImageHeight);
$('#lightbox-image').width(intImageWidth);
var intCurrentWidth = $('#lightbox-container-image-box').width();
var intCurrentHeight = $('#lightbox-container-image-box').height();
// Get the width and height of the selected image plus the padding
var intWidth = (intImageWidth + (settings.containerBorderSize * 2)); // Plus the image´s width and the left and right padding value
var intHeight = (intImageHeight + (settings.containerBorderSize * 2)); // Plus the image´s height and the left and right padding value
// Diferences
var intDiffW = intCurrentWidth - intWidth;
var intDiffH = intCurrentHeight - intHeight;
// Perfomance the effect
$('#lightbox-container-image-box').animate({ width: intWidth, height: intHeight },settings.containerResizeSpeed,function() { _show_image(); });
if ( ( intDiffW == 0 ) && ( intDiffH == 0 ) ) {
if ( $.browser.msie ) {
___pause(250);
} else {
___pause(100);
}
}
$('#lightbox-container-image-data-box').css({ width: intImageWidth });
$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ height: intImageHeight + (settings.containerBorderSize * 2) });
};
AND
$('#gallery a').lightBox( maxHeight: null,
maxWidth: null);
});
But whenever I do this and click on the image just gets open in browsers annother tab, all the lightbox functinalty fails
Please help me to correct it
Thanks
I modified the jquery.lightbox-0.5.js file by Leandro Vieira Pinho. What this modified javascript file does is, it will check each image and if the width or height exceeds the screen (viewport area), then the image is resized while preserving the aspect ratio.
To use this file, you just have to copy and paste entire contents of this javascript file in your already existing jquery.lightbox-0.5.js file or you just have to replace the old file with this.
I have given 2 links: First one will let you down load the entire javascript file and the second will display the source code which you can copy and paste into your existing jquery.lightbox-0.5.js.
Download javascript file: http://turboupload.com/081zwttawcb6
Source code : http://www.sourcepod.com/twhbtf88-5047
You need to specify the maxHeight and maxWidth against all calls of the lightbox().
Example:
$('#gallery a').lightBox({
maxHeight: 700,
maxWidth: 700
});
You lightbox call is missing a {.
Change your lightbox call to as follows:
$('#gallery a').lightBox( {maxHeight: null,
maxWidth: null
});
Sunimal Kaluarachchi's code works well but doesn't handle a landscape aspect ratio properly.
To work properly you need to change
if ( newViewPortWidth > viewPortHeight ) // if viewport width > viewport height
to
if ( newImageWidth > newViewPortWidth ) //
in his function ___calculateImageDimension function
here is the complete function
function ___calculateImageDimension(viewPortWidth, viewPortHeight, imageWidth, imageHeight)
{
// obtain 82% of ViewPort Height
var viewPortHeightPercent = viewPortHeight * (82/100);
var newImageHeight = imageHeight;
var newImageWidth = imageWidth;
var newViewPortWidth = viewPortWidth;
var scaleHeight =0;
var scaleWidth = 0;
// if ( newViewPortWidth > viewPortHeight ) // if viewport width > viewport height
if ( newImageWidth > newViewPortWidth ) // if viewport width > viewport height
{
// Get 80% of current viewport width so the image width will be displayed within this 80% of viewport width size
newViewPortWidth = viewPortWidth * (80/100);
}
// image width check
if ( newImageWidth > newViewPortWidth )
{
newImageWidth = newViewPortWidth;
scaleWidth = imageHeight/imageWidth;
newImageHeight = scaleWidth * newImageWidth;
}
// image height check
if ( newImageHeight > viewPortHeightPercent )
{
newImageHeight = viewPortHeightPercent;
//calculate scale to set width
scaleHeight = imageWidth/imageHeight;
newImageWidth = scaleHeight * newImageHeight;
}
arrayNewImageSize = new Array(newImageWidth,newImageHeight);
return arrayNewImageSize;
}
Your function should replace the one in the jquery.lightbox.js plugin file (look for the function that starts with function _resize_container_image_box somewhere around line 196).
What you need to do next is call lightBox()in your external JS file or inside html like #cocacola09 and #Chandu suggested:
$('#gallery a').lightBox( {maxHeight: null,
maxWidth: null
});
What i did in addition is to get the width and height of a window dynamically, so it fits the current window size:
$(function() {
//get height and width of window
var windowWidth = $(window).width();
var windowHeight = $(window).height();
//windowsize - 50px
var windowHeightFixed = windowHeight - 50;
var windowWidthFixed = windowWidth - 50;
$('a.lightbox').lightBox({
maxHeight: windowHeightFixed,
maxWidth: windowWidthFixed
});
});
But this method gives some buggy results. The problem occurs when you reload the page in a different window size. Some images preserve the width/height of previous window size, but some don't. Tested in Firefox 18, Chrome 24.

jQuery resize to aspect ratio

How would I resize a image in jQuery to a consistent aspect ratio. For example setting maximum height and have the width resize correctly. Thanks.
Here's a useful function that might do what you want:
jQuery.fn.fitToParent = function()
{
this.each(function()
{
var width = $(this).width();
var height = $(this).height();
var parentWidth = $(this).parent().width();
var parentHeight = $(this).parent().height();
if(width/parentWidth < height/parentHeight) {
newWidth = parentWidth;
newHeight = newWidth/width*height;
}
else {
newHeight = parentHeight;
newWidth = newHeight/height*width;
}
var margin_top = (parentHeight - newHeight) / 2;
var margin_left = (parentWidth - newWidth ) / 2;
$(this).css({'margin-top' :margin_top + 'px',
'margin-left':margin_left + 'px',
'height' :newHeight + 'px',
'width' :newWidth + 'px'});
});
};
Basically, it grabs an element, centers it within the parent, then stretches it to fit such that none of the parent's background is visible, while maintaining the aspect ratio.
Then again, this might not be what you want to do.
You could calculate this manually,
i.e.:
function GetWidth(newHeight,orginalWidth,originalHeight)
{
if(currentHeight == 0)return newHeight;
var aspectRatio = currentWidth / currentHeight;
return newHeight * aspectRatio;
}
Make sure you use the ORIGINAL values for the image otherwise it will degrade over time.
EDIT: example jQuery version (not tested)
jQuery.fn.resizeHeightMaintainRatio = function(newHeight){
var aspectRatio = $(this).data('aspectRatio');
if (aspectRatio == undefined) {
aspectRatio = $(this).width() / $(this).height();
$(this).data('aspectRatio', aspectRatio);
}
$(this).height(newHeight);
$(this).width(parseInt(newHeight * aspectRatio));
}
Use JQueryUI Resizeable
$("#some_image").resizable({ aspectRatio:true, maxHeight:300 });
aspectRatio: true -> maintain original aspect ratio
There's no accounting for the amount of copy and pasters out there eh! I also wanted to know this and all I saw were endless examples of scaling width OR height.. who would want the other overflowing?!
Resize width AND height without the need for a loop
Doesn't exceed the images original dimensions
Uses maths that works properly i.e width/aspect for height, and height*aspect for width so images are actually scaled properly up and down :/
Should be straight forward enough to convert to javascript or other languages
//////////////
private void ResizeImage(Image img, double maxWidth, double maxHeight)
{
double srcWidth = img.Width;
double srcHeight = img.Height;
double resizeWidth = srcWidth;
double resizeHeight = srcHeight;
double aspect = resizeWidth / resizeHeight;
if (resizeWidth > maxWidth)
{
resizeWidth = maxWidth;
resizeHeight = resizeWidth / aspect;
}
if (resizeHeight > maxHeight)
{
aspect = resizeWidth / resizeHeight;
resizeHeight = maxHeight;
resizeWidth = resizeHeight * aspect;
}
img.Width = resizeWidth;
img.Height = resizeHeight;
}
This is a good solution if you need perfect height and width aspect ratio after crop it will give perfect crop ratio
getPerfectRatio(img,widthRatio,heightRatio){
if(widthRatio < heightRatio){
var height = img.scalingHeight - (img.scalingHeight % heightRatio);
var finalHeight = height
var finalWidth = widthRatio * (height/heightRatio);
img.cropHeight = finalHeight;
img.cropWidth = finalWidth
}
if(heightRatio < widthRatio){;
var width = img.scalingWidth - (img.scalingWidth % widthRatio);
var finalWidth = width;
var finalHeight = heightRatio * (width/widthRatio);
img.cropHeight = finalHeight;
img.cropWidth = finalWidth
}
return img
}

Categories