(Javascript/CSS) resizing function not working - javascript

I have a container div that has to fit in two different types of pictures. Some pictures are 'potrait', width:533px and height:801px, others are 'landscape', width:800px and height:533px.
So to make the div size change to accommodate for the pictures, I wrote the function described below (the 'photos' var is an array of pictures and the [i] is a variable for changing through them and 'img' is a var that fetches the #container element)
function resize() {
var width = photos[i].clientWidth;
var height = photos[i].clientHeight;
if (width + height === 1333) {
img.style.width="800px";
img.style.height="533px";
}
else if (width + height === 1334) {
img.style.width="533px";
img.style.height="801px";
}
}
Then, I placed this function in the next and back functions for switching between the pictures,
function next() {
img.src = photos[i];
el.innerHTML = caption[i];
resize();
if (i<photos.length-1){
i=i+1;
} else {
i=0;
}
}
The next and back functions work, but when they get to the pictures that needed to be resized, the container holds the same dimensions that were preset in the CSS.(the preset widht/height in the CSS is for the landscape pictures, because I only have 2 potrait pictures that the div needs to change its size to.
#container {
height: 533px;
width: 800px;
overflow:hidden;
}
I tried looking at other resize threads but whereas people have needed a way to get only a dynamic width or height, I need both to be that way. I think the problem lies in the "clientWidth/Height" property which I thought gets the width/height of the object before the '.' And i'm not sure if I should set the CSS container div to have a height or leave it to "auto" or a certain percentage. I'd appreciate any help on the matter :)

Related

Containing element's width is not displayed correctly

Several images are placed into an element whose display is flex and flex-wrap set to nowrap. The images don't fit into the element's width and extend beyond the screen width.
I am trying to calculate the width of the element that includes the images. However the width of element is always equal to screen width whereas it should be much greater than screen width.
Several threads have advised to first check if all the images have been loaded. Following is the code used to check the loading of the images.
let len = allCarousalImagesList.length,
counter = 0;
[].forEach.call( allCarousalImagesList, function( img ) {
if(img.complete)
incrementCounter();
else
img.addEventListener( 'load', incrementCounter, false );
} );
function incrementCounter() {
counter++;
if ( counter === len ) {
let carousalWidth = carousalElement.offsetWidth;
let browserWidth = window.innerWidth;
console.log(browserWidth, carousalWidth);
}
}
Inspite of checking for the loading of images, the width of the element containing unwrapped images is not being displayed correctly and is equal to screen width. I am using offsetWidth to get the width. Please help with this issue.
The code has been uploaded on the codesandbox here
So I created a solution to your problem:
And make sure to add position:absolute; to your carousal class
window.addEventListener("load", function () {
let carousalElement = document.getElementsByClassName("carousal")[0];
var width_of_img_container = window.getComputedStyle(carousalElement).width;
console.log(width_of_img_container);
},false);
Hope I could help.

resize divs to auto and then to same height as one another upon window resize?

I have three column divs I would like to resize so that they are all the same lenghth. I have been able to do this upon page load by executing the following function (which I found on SO though unfortunately I am unable to find it now to give attribution, will update if I can find it):
function resizeIt()
{
var largest = 0;
$(".feature").each(function(){ //loop through each section
var findHeight = $(this).height(); //find the height
if(findHeight > largest){ //see if this height is greater than "largest" height
largest = findHeight; //if it is greater, set largest height to this one
}
});
$(".feature").css({"height":largest+"px"});
}
This works fine, but I also want the divs to resize each time the window resizes. So I modified the function and then call it each time the window resizes and call the function then as well as upon page load. Here is the modified function (first line of function is the addition) plus the function call for a window resize:
function resizeIt()
{
$(".feature").css({"height: auto"});
var largest = 0;
$(".feature").each(function(){ //loop through each section
var findHeight = $(this).height(); //find the height
if(findHeight > largest){ //see if this height is greater than "largest" height
largest = findHeight; //if it is greater, set largest height to this one
}
});
$(".feature").css({"height":largest+"px"});
}
resizeIt();
$(window).resize(function(){
resizeIt();
});
Now my div's do not resize properly upon page load or upon page resize. Nothing happens at all. If I put some kind of alert in my function, it is not called when the
$(".feature").css({"height: auto"});
line is included in the function. Why is this line breaking my code? The object does exist when I call it on the first line, so it's not a null object.
Why not try resizing with media queries? This will allow the divs to resize upon window resizing without need for page reload
#media (max-width: 1200px) {
.feature {
/*new height value*/
/*new width value*/
}
}
#media (max-width: 767px) {
.feature {
/*new height value*/
/*new width value*/
}
}

JavaScript: Get window width minus scrollbar width

Ok, I thought this would be really simple, but it's turning out not to be. I think I'm just messing something up in my HTML/CSS, but here goes.
I have a basic page like so:
HTML
<!DOCTYPE html>
<html>
<head>
<link href='test2.css' rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="test2.js"></script>
</head>
<body>
<div id="scroll"></div>
</body>
</html>
test2.css
* {
padding: 0;
margin: 0;
}
html, body {
height: 100%;
width: 100%;
}
#scroll {
height: 100%;
width: 100%;
overflow: scroll;
background-color: black;
}
test2.js
$(document).ready(function() {
// my resolution is 1440x900
alert('innerwidth should be 1425');
// all of these return 1440
alert('body innerwidth: ' + $('body').innerWidth());
alert('document width: ' + $(document).width());
alert('window width: ' + $(window).width());
alert('scroll div innerwidth: ' + $('#scroll').innerWidth());
alert('document.documentElement.clientWidth: ' + document.documentElement.clientWidth);
alert('document.documentElement.scrollWidth: ' + document.documentElement.scrollWidth);
});
So I've got one element on the page... a div that takes up the entire screen, or rather it should be taking up the entire screen minus the scrollbars. Now, I've been doing some snooping on how to grab the width and height of a page without the scrollbars, but unfortunately, none of them return the proper value... which makes me believe I'm missing the boat in my HTML or CSS.
I looked at the following:
jquery - how to get screen width without scrollbar?
how to get the browser window size without the scroll bars
So what I need is for a method to return the value of my viewable screen minus the respective scrollbar value... so for my width, my value should be 1425 because the scrollbar is 15 pixels wide. I thought that's what innerWidth's job was, but apparently I'm wrong?
Can anyone provide any insight? (I'm running Firefox 24.)
EDIT
To add some background, I've got a blank page. I will be adding elements one by one to this page, and I need to use the width of the page when calculating the sizes for these elements. Eventually, this page will grow and grow until the scrollbar appears, which is why I'm trying to force the scrollbar there from the start, but apparently, that still doesn't do anything.
EDIT2
Here's something even more interesting... if I do document.getElementById('scroll').clientWidth, I get the proper innerWidth, but if I do $('#scroll').width() or $('#scroll').innerWidth(), they both return the max resolution... sounds like a jQuery bug.
I got this somewhere and would give credit if I knew where, but this has been succesfull for me. I added the result as padding when setting the html overflow to hidden.
Problem is that the scrollbar is a feature of the browser and not the web page self. Measurement should be done dynamically. A measurement with a scrollbar and a measurement without a scrollbar will resolve into calculating the difference in width.
Found the source: http://www.fleegix.org/articles/2006/05/30/getting-the-scrollbar-width-in-pixels
scrollCompensate = function () {
var inner = document.createElement('p');
inner.style.width = "100%";
inner.style.height = "200px";
var outer = document.createElement('div');
outer.style.position = "absolute";
outer.style.top = "0px";
outer.style.left = "0px";
outer.style.visibility = "hidden";
outer.style.width = "200px";
outer.style.height = "150px";
outer.style.overflow = "hidden";
outer.appendChild(inner);
document.body.appendChild(outer);
var w1 = inner.offsetWidth;
outer.style.overflow = 'scroll';
var w2 = inner.offsetWidth;
if (w1 == w2) w2 = outer.clientWidth;
document.body.removeChild(outer);
return (w1 - w2);
}
var htmlpadding = scrollCompensate();
The correct answer is in this post marked as accepted:
CSS media queries and JavaScript window width do not match
This is the correct code:
function viewport() {
var e = window, a = 'inner';
if (!('innerWidth' in window )) {
a = 'client';
e = document.documentElement || document.body;
}
return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}
Discovered a very hacky solution... by adding this before my alerts in test2.js, I get the proper width:
var p = $('body').append('<p style="height: 100%; width: 100%;"></p>');
alert(p.width());
$('body').remove('p');
And consequently, all of the alerts now have the proper width. I also don't even need overflow-y in the CSS if I do it this way. Curious why this solves it...
The real answer should be keeping the HTML and CSS as is, then using document.getElementById('scroll').clientWidth. Using clientWidth gets the viewable area minus the scrollbar width.
The correct width of the page is given by $(document).width().
Your problem is that you're using a scroll within the div (overflow: scroll).
Using $(document).width() the returned value is already discounting the visible width of the scroll, but how do you put a scroll within the div value returned is no longer the same.
As the width of the scroll is not standard and varies from system to system and browser to browser, it is difficult to solve.
I suggest you remove the scroll of the div and let the browser manage this by default in the body, then yes you have the correct width.

element.height returns visible height - I want total?

So apparently this is only happening to me - and I can't think why but if it works, I'm happy :)
I have a full screen slideshow and I have created a function that will vertically center any images that are too large.
function fixImages(){
maxheight = $('.index-slide-container').height();
$('.index-slide-container img').each( function(index, ele){
if (ele.height > maxheight){
offset = ( maxheight - ele.height ) / 2;
$(ele).css('top', offset + 'px');
}
});
}
fixImages();
However, ele.height returns the height of the visible part of the image (the height of it's container, as it has overflow:hidden, even though when I console.log(ele) and expand the element, 'height' is clearly the correct value.
I have also tried $(ele).height(), $(ele).css('height'), $(ele).outerHeight() and ele.clientHeight; all of which return the same.
Thanks
I made some tests, and $('img').height(); is giving me the right height of the picture.
If you wish to center the picture vertically why don't you use the absolute positioning with css like this for example :
.index-slide-container img {
position:absolute;
top:50%;
}
And than, you could set the negative margin programmatically with jQuery :
$('.index-slide-container img').each( function(i, e){
var height = $(e).height() / 2;
$(e).css({'margin-top':'-'+height});
});

Dynamic Image Resizing

I have an image on a webpage that needs to be stretched to fit the available space in the window whilst maintaining its proportion. Here's what I've got:
http://www.lammypictures.com/test/
I would like the large image to proportionally stretch to match the height and widths of the browser, minus the size of the divs to the left and bottom.
So the problem is 2 fold really; first i need to get the max height and width minus the link and image bars, secondly i need to resize the image on a browser resize whilst maintaining proportions.
Any help would be much appreciated.
Cheers
CIP
You could try using jQuery ui scaling effect:
$(document).ready(function () {
resizeImage(); // initialize
$(window).resize(function () {
resizeImage(); // initialize again when the window changes
});
function resizeImage() {
var windowHeight = $(window).height() - $('#nav').height(),
windowWidth = $(window).width(),
percentage = 0;
if (windowHeight >= windowWidth) {
percentage = (windowWidth / $('#image').width() ) * 100;
}
else {
percentage = ( windowHeight / $('#image').height() ) * 100;
}
$('#image').effect('scale', { percent : percentage }, 1);
};
});
Tested and works great, however, a few tweaks maybe needed to get it just the way you like it.
You may just not setup the image element width and height attributes, and write next styles:
.hentry img { max-width: 100%; }
And it will shrink relative to the minimum side.
P.S. But not in position: absolute; block which not have any size. Set up the parent block to relative positioning.

Categories

Resources