Resizable / fluid images wrapped in a div? - javascript

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

Related

Jquery transition Opacity based on var value

I am trying to animate an opacity value from 0 to 1, based on the scroll position within the viewport height. The code below sets variables for windowHeight and scrollTop, which can be combined to calculate percentageScrolled (0–100) of the viewport height. Based on this I am able to switch CSS values at set points, but instead I want to gradually change the opacity from 0–100 of percentageScrolled.
How can I adjust the code below to transition/animate the opacity?
Thanks.
$(window).on('scroll', function(){
// Vars
var windowHeight = $(window).height();
var scrollTop = $(this).scrollTop();
var percentageScrolled = (scrollTop*100)/windowHeight;
if( percentageScrolled < 100 ) {
$('.colour-overlay').css('opacity', '1');
} else {
$('.colour-overlay').css('opacity', '0');
}
});
You can remove the if and set the opacity to the percentage divided by 100
$(window).on('scroll', function() {
// Vars
var windowHeight = $(window).height();
var scrollTop = $(this).scrollTop();
$('.colour-overlay').css('opacity', scrollTop / windowHeight);
});
.colour-overlay {
display: block;
width: 20px;
height: 1200px;
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="colour-overlay"></div>
$(‘.colour-overlay’).css(opacity, percentageScrolled / 100);
Instead of if else statement.
Also as a general advice try to avoid using var, use const or let instead and if your project doesnt depend on jquery try to avoid it too.
const overlays = document.querySelectorAll(‘.colour-overlay’);
window.addEventListener('scroll', () => {
const windowHeight = window.offsetHeight;
const scrollTop = window.scrollTop;
const percentageScrolled = (scrollTop * 100) / windowHeight;
for (const overlay of overlays) {
overlay.style.opacity = percentageScrolled / 100;
}
});
This would be the pure js solution.
Dont know if i understood you right, but a wrote an example have a look.
$(document).on('scroll', function(){
// Vars
// use body instead of window, body will return the right height where window will return the view size
var windowHeight = $("body").height();
var scrollTop = $(this).scrollTop();
var percentageScrolled = Math.abs((((scrollTop / windowHeight) * 100) / 100 ));
$('.colour-overlay').css('opacity', percentageScrolled);
});
.colour-overlay{
background:red;
height:1000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="colour-overlay"></div>

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.

Keep aspect ratio of div when resizing window

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 {

javascript image resizing in jquery

I came upon a script for resizing images dynamically for fitting a specific width here. I modified it for my own web app and it works great part of the time, but for some reason the function will sometimes randomly not trigger the if statement when the image does indeed have a larger width then I’m desiring so the image never resizes. I put in a set timeout hoping that the timeout would give the browser time to read the image. But no luck any ideas as to why it would not trigger?
Side note: this is for a mobile web app, is there something with HTML5 that I could use?
var maxWidth = 200;
var imgWidth = $('#locImg').width();
console.log(imgWidth);
setTimeout(function () {
if( imgWidth > maxWidth) {
newWidth = maxWidth;
var newHeight = $('#locImg').height() / ( $('#locImg').width() / maxWidth);
$('#locImg').height(newHeight).width(newWidth);
console.log($('#locImg').width());
$('#loc').css('visibility','visible');
}
else {
$('#loc').css('visibility','visible');
}
},750);
You could use something like this to ensure the image is fully loaded:
var maxWidth = 200;
var imgWidth = $('#locImg').width();
var image = new Image();
image.src = $('#locImg').attr("src");
image.onload = (function () {
if( imgWidth > maxWidth) {
newWidth = maxWidth;
var newHeight = $('#locImg').height() / ( $('#locImg').width() / maxWidth);
$('#locImg').height(newHeight).width(newWidth);
console.log($('#locImg').width());
$('#loc').css('visibility','visible');
}
else {
$('#loc').css('visibility','visible');
}
});
this way it only starts the resize after the image has fully loaded.

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