Containing element's width is not displayed correctly - javascript

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.

Related

Is Javascript an Effective Method of Creating Fluid Layouts?

I'd like opinions on whether or not Javascript is a still a viable and relatively effective method of producing fluid website layouts. I know that it is possible to create fluid layouts with Javascript, but relative to other methods (e.g. CSS3/HTML5) how does it stand up in terms of performance and complexity? The function below represents what I mean. In the function, javascript is being used to find the dimensions of various elements and place other elements accordingly. To see it working, follow this link.
function onPageResize() {
//center the header
var headerWidth = document.getElementById('header').offsetWidth; //find the width of the div 'header'
var insideHeaderWidth = (document.getElementsByClassName('header')[0].offsetWidth + document.getElementsByClassName('header')[1].offsetWidth + document.getElementById('logoHeader').offsetWidth); //find the combined width of all elements located within the parent element 'header'
document.getElementsByClassName('header')[0].style.marginLeft = ((headerWidth - insideHeaderWidth) / 2) + "px"; //set the margin-left of the first element inside of the 'header' div
/////////////////////////////////////////////////////////////////
//justify alignment of textboxes
var subtitleWidth = document.getElementsByClassName('subtitle'); //assign the properties of all elements in the class 'subtitle' to a new array 'subtitleWidth'
var inputForm = document.getElementsByClassName('inputForm'); //assign the properties of all elements in the class 'inputForm' to a new array 'inputForm'
for (i = 0; i < inputForm.length; i++) { //for every element in the array 'inputForm' set the margin-left to dynamically place the input forms relative to eachother
inputForm[i].style.marginLeft = (subtitleWidth[4].offsetWidth - subtitleWidth[i].offsetWidth) + "px";
}
/////////////////////////////////////////////////////////////////
//place footer on absolute bottom of page
if (window.innerHeight >= 910) { //when the page is larger than '910px' execute the following
var totalHeight = 0; //initialize a new variable 'totalHeight' which will eventually be used to calulate the total height of all elements in the window
var bodyBlockHeight = document.getElementsByClassName('bodyBlock'); //assign the properties of all elements in the class 'bodyBlock' to a new array 'bodyBlockHeight'
for (i = 0; i < bodyBlockHeight.length; i++) { //for every instance of bodyBlockHeight in the array, add the height of that element into the 'totalHeight'
totalHeight += bodyBlockHeight[i].offsetHeight;
}
totalHeight += document.getElementById('header').offsetHeight; //finally, to add the height of the only element that has yet to be quantified, include the height of the element 'header' into the 'totalHeight'
/*Set the margin-top of the element 'footer' to the result of subtracting the combined heights of all elements in the window from the height of the window.
This will cause the footer to always be at the absolute bottom of the page, despite whether or not content actually exists there. */
document.getElementById('footer').style.marginTop = (window.innerHeight - totalHeight) - document.getElementById('footer').offsetHeight + "px";
} else {
//if the page height is larger than 910px (approx the height of all elements combined), then simply place the footer 20px below the last element in the body
document.getElementById('footer').style.marginTop = "20px"
}
/////////////////////////////////////////////////////////////////
}
Again, the result of the above function can be viewed at this link.
Thank you to any and all who offer their opinions!
You should be using CSS rather than JavaScript because that is what CSS is designed to do. If you want a fluid layout play around with using percentage widths, floats and media queries.

(Javascript/CSS) resizing function not working

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 :)

How to get function of both position values: Fixed and Absolute?

I have a fullscreen background image. I also have a pop-out sidebar.
When the sidebar pops out it re-sizes the background image smaller so as to not cut it off by covering over it. When the sidebar is retracted then the image enlarges back.
I can only get this effect if the background image has a position value of absolute. However that value also doesn't let you scroll without the background ending and getting blank space or having to repeat the image to fill the blank space.
When I make the position value fixed then it solved the blank space issue, but no longer re-sizes the background image when you open the sidebar, it covers up part of the background as you'd expect.
How do I get the effects of both the position values of Fixed and Absolute? I want it to scroll indefinitely without having to duplicate the image, but also re-size when the sidebar is opened.
Here is the theme I'm using that illustrates my problem: http://themes.themolitor.com/wpzoom/2011/04/first-blog-post-title/
$(function() {
$('#openSidebar').click(function() {
if ( $('#sidebar').width() == 300 ) {
var y = window.innerWidth;
$("#imageContainer").width(y-300);
}
else {
$('#sidebar').width(0);
$('#imageContainer').width("100%");
}
});
$('#closeSidebar').click(function() {
if ( $('#sidebar').width() == 300 ) {
var y = window.innerWidth;
$("#imageContainer").width(y);
}
else {
$('#sidebar').width(0);
$('#imageContainer').width("100%");
}
});
});
Actually thats easier. Obviously you will have a button that opens your sidebar when you click it. Considering your sidebar is on the right (like your example theme) you just need to resize bg's width and leave height as it is. So this is the code:
document.getElementById("sidebar-button").addEventListener("click", doStuff, false);
doStuff = function() {
var sb = document.getElementById("sidebar");
var bgnd = document.getElementById("bg");
if ( sb.style.width == 0 ) {
sb.style.width = "300px";
var y = window.innerWidth;
bgnd.style.width = y - 300 + "px";
}
else {
sb.style.width = "0px";
bgnd.style.width = "100%";
}
};
But you still need the the idea of window.onresize so you can adjust bg's width correctly.
EDIT:
$(function() {
$('#sidebar-button').click(function() {
if ( $('#sidebar').width() == 0 ) {
$('#sidebar').width( 300 );
var y = window.innerWidth;
$("#bg").width(y-300);
}
else {
$('#sidebar').width(0);
$('#bg').width("100%");
}
});
});
I just tested and works just fine, the only difference is that it use jQuery.
Well here is an example:
Lets say the background is a div with id #bg then all you have to do is to resize the bg when the window is resized using javascript considering when your window starts to be scrollable. If for example your windows starts to be X-scrollable when its width is 800px or less and Y-Scrollable when its height is 500px:
window.onresize = function() {
if ( window.width < 800 ) document.getElementById("#bg").style.width = "800px";
else document.getElementById(#bg).style.width = "100%";
if ( window.height < 500 ) document.getElementById("#bg").style.height = "500px";
else document.getElementById("#bg").style.height = "100%";
}
Hope this helps you.

Change image in html keeping size javascript

I am experimenting an issue while changing an image in a img tag of html.
I did an example in fiddle which works as my webpage with images I found on internet so they are not equal:
http://jsfiddle.net/kZp7V/
This is the script code:
var counterImage = 0;
var ccI = new Array('http://tiendas.fnac.es/la-canada/files/2010/12/Peque%C3%B1a-orquesta-mediterr%C3%A1neo-300x286.jpg',
'http://muack.es/wp-content/uploads/2013/04/smalldata1.jpg',
'https://pbs.twimg.com/profile_images/604644048/sign051.gif'
);
window.image = function(element){
if(counterImage < 3){
document.getElementById("EJ_test").setAttribute('src', ccI[counterImage]);
counterImage++;
}
else{
document.getElementById("EJ_test").setAttribute('src', ccI[0]);
counterImage = 1;
}
}
I want that all images to have the same aspect of the first one, I mean, same hight and width. Is is possible?
I was asked to do it with photoswipe but I find it a little bit difficult so I want to do this now and then, read carefully everything about photoswipe for next week.
EDIT: I changed the class="cropTest" to the div instead of the image and now all images are "resized". I use "" because they are smaller. The img tag adjust to the image but I don't want this happends. I want to have a diferent image but keeping the size. I don't mind the image looks blur or pixelated.
you can use getComputedStyle to get the current size of the image, and use that information once, for example by checking if the width style has already been set by you. Example:
window.image = function(element){
if (!document.getElementById("EJ_test").style.width) {
var currentStyle = window.getComputedStyle(document.getElementById("EJ_test"));
document.getElementById("EJ_test").style.width =
currentStyle.width;
document.getElementById("EJ_test").style.height =
currentStyle.height;
}
if(counterImage < 3){
document.getElementById("EJ_test").setAttribute('src', ccI[counterImage]);
counterImage++;
}
else{
document.getElementById("EJ_test").setAttribute('src', ccI[0]);
counterImage = 1;
}
}

Script that makes all floating divs the same height

Hey there, I have 20 divs floated left with different height. I use this script to resize them. It worked perfect when my website was designed using pixels.
When i have changed my website to % design (percentage design), the script stopped working that reliable, sometimes it does not resize.
can you take a look, see if there are any adjustments needed for liquid layouts?
maybe it's the way i call the script?
Ty very much
Here it is:
var currentTallest = 0;
var currentRowStart = 0;
var rowDivs = new Array();
function setConformingHeight(el, newHeight) {
// set the height to something new, but remember the original height in case things change
el.data("originalHeight", (el.data("originalHeight") == undefined) ? (el.height()) : (el.data("originalHeight")));
el.height(newHeight);
}
function getOriginalHeight(el) {
// if the height has changed, send the originalHeight
return (el.data("originalHeight") == undefined) ? (el.height()) : (el.data("originalHeight"));
}
function columnConform() {
// find the tallest DIV in the row, and set the heights of all of the DIVs to match it.
$('div.column').each(function(index) {
if(currentRowStart != $(this).position().top) {
// we just came to a new row. Set all the heights on the completed row
for(currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) setConformingHeight(rowDivs[currentDiv], currentTallest);
// set the variables for the new row
rowDivs.length = 0; // empty the array
currentRowStart = $(this).position().top;
currentTallest = getOriginalHeight($(this));
rowDivs.push($(this));
} else {
// another div on the current row. Add it to the list and check if it's taller
rowDivs.push($(this));
currentTallest = (currentTallest < getOriginalHeight($(this))) ? (getOriginalHeight($(this))) : (currentTallest);
}
// do the last row
for(currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) setConformingHeight(rowDivs[currentDiv], currentTallest);
});
}
$(window).resize(function() {
columnConform();
});
$(document).ready(function() {
columnConform();
});
Well if you change it to fluid layout (% design) then you are going to have to add a window resize listener, basically when the resize event is done or while it's running you need to recall the script so it can recalculate with new dimensions, you did not need to doo that with pixels because it was a fixed size and once assigned will not change no matter how many times you resize the actual screen.
If you use styles like this:
<style>
.parent{
background:#F00;height:300px
}
.parent div{
float:left;height:100%;width:33.33%;
}
</style>
<div class="parent">
<div style="background:#FED"></div>
<div style="background:#EDF"></div>
<div style="background:#DFE"></div>
</div>
You just have to set the height of the parent div, and the width of the children div

Categories

Resources