I get $(image).width() == 0 even when placed inside $(window).load - javascript

I want to resize images that are bigger than the window, but I keep getting 0 width and height when I try to get the image size. I read somewhere that it could be because images aren't necessarily loaded at (document).ready so image functions should go under (window).load, but it's no use. I'm a real newbie when it comes to jquery and javascript so I could be doing something wrong.
This is how my javascript file looks:
//<!--
$(document).ready(function(){
...
});
$(window).load(function () {
$(".lightbox img").each(function() {
var width = $(this).width();
var max_width = $(window).width()-30;
var height = $(this).height();
var max_height = $(window).height()-30;
if(width > max_width || height > max_height) {
if(height > width) {
height = max_height;
width = Math.ceil(width / height * max_height);
} else {
width = max_width;
height = Math.ceil(height / width * max_width);
}
}
$(this).attr("width",width);
$(this).attr("height",height);
});
});
//-->
Thanks in advance.

Take a look at this project that provides a callback when images have loaded.
Another reason you could be getting no dimensions is an invisible element (parent or self).

Try $(this).css("width") instead of attr

When the window loads, the images haven't necessarily loaded yet. JavaScript can't get an image's dimensions until is has completely loaded, and until then, you get a computed value of zero.
Bearing this in mind, a repeating loop might help. (Warning: haven't tested)
var width = 0;
while (!width) {
width = $(this).width();
}
Watch out for infinite loops, though.

Related

Change height of element on resize

Hello guys I'm trying to change height of my element dynamically.
These are my variables.
var windowWidth = 1440;
var currentWidth = $(window).width();
var elementHeight = $('#line4').height();
Now what I want is when difference between window width and current width is lower then 6 I want to change height of my element. I want to do this every time when (windowWidth - currentWidth)<6. So every time when window resizes and it's lower then 6 I want to change height of element by minus 14px. This is what I've tried.
$( window ).bind("resize", function(){
if((windowWidth - currentWidth)<6) {
$("#line4").css('height', elementHeight-14);
}
});
It does not work and I don't know what I'm missing. Also follow up question can I change other CSS properties this way. For this particular problem I will also need to change css top property in the same way, because I have some div with absolute position.
You need to measure the current width of the window on every resize event, since it's changing too.
var windowWidth = 1440;
var currentWidth = $(window).width();
var elementHeight = $('#line4').height();
$( window ).bind("resize", function(){
currentWidth = $(window).width()
if((windowWidth - currentWidth)<6) {
$("#line4").css('height', elementHeight-14);
}
});
You need to get windowWidth each time resize event called
And you should add debounce into resize event for better performance.
I often do like this, maybe you can search any better way:
var resizeTimer;
$(window).on('resize', function(e) {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function() {
// Run code here, resizing has "stopped"
currentWidth = $(window).width()
if((windowWidth - currentWidth)<6) {
$("#line4").css('height', elementHeight-14);
}
}, 250);
});
and I created this to test, you can try it. Btw i increase from 6 to 600 to check easier :D
https://codepen.io/huytran0605/pen/NgBEVO

Get constant browser height and width

I was wondering how I could constantly get the current browser's height and width. Right now, I am using jQuery and have something like this:
var height = window.innerHeight;
var width = window.innerWidth;
This does initially work as it gets the screen when the page is loaded up. However, when the user changes the screen width/height manually, I can't seem to get the current dimensions and the page starts faulting with errors. How should I be checking the dimensions at all times? I've tried googling the answer but I can't seem to find anything applicable, though I'm sure many others have had the same issue (I don't think I'm searching up the right keywords!). Please let me know what I can do!! Thanks!
Use a window.onresize function as well as a window.onload handler to update the width and height variables.
(Resizeable Demo)
var width,height;
window.onresize = window.onload = function() {
width = this.innerWidth;
height = this.innerHeight;
document.body.innerHTML = width + 'x' + height; // For demo purposes
}
Using jQuery objects it would look like this.
(Resizeable Demo)
var width,height;
$(window).on('load resize', function() {
width = this.innerWidth; // `this` points to the DOM object, not the jQuery object
height = this.innerHeight;
document.body.innerHTML = width + 'x' + height; // For demo purposes
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Try this:
$(window).on("resize",function(){
console.log($(this).height() + " " + $(this).width());
});
fiddle
Try this
var width = window.outerWidth;
var height = window.outerHeight;
To resize the current window, use
window.resizeTo(width, height);
You can trigger the resize function using:
$( window ).resize(function() {
//....
});
Hope it helps you
You can use this to detect a change in screen size:
$(window).resize(function() {
height = window.innerHeight;
width = window.innerWidth;
//other code you wish to run on screen size change;
});
This assumes that height and width were declared in a scope that the function has access to. Otherwise make sure to place var before each variable.

Changing the background image according to resolution - javascript only

there's a lot of this question scattered over stackoverflow, but I can't seem to find an answer that specifically suits my situation.
I have made a background in HD 1920x1080 for a school project I'm making, and I'm trying to make it fit for every resolution there is. So what I did was resizing this image for every specific resolution, putting me in an awkward spot to code it, as I cannot use jQuery, I'm not allowed to.
I'm thinking of using the screen.width property, but I'd need a length too as I have multiple backgrounds with the ...x768 resoulution.
Is there anyone who'd be able to tell me how to change my body's background, depending on the user's height and width of the screen?
Thank you very much,
Michiel
You can use window.innerWidth and window.innerHeight to get the current dimensions of your browser's window.
Which means that if your browser takes half of your 1920x1080 desktop, it'll compute to something like:
window.innerWidth ~= 540
window.innerHeight ~= 1920 // actually something smaller because it doesn't count your browser's chrome
Your window can of course change size, and if you want to handle that, you can listen to the event "resize" for your window:
window.addEventListener('resize', function () {
// change background
});
To change the body's background without jQuery, you can do something like this:
document.body.style.backgroundImage = "url(/* url to your image...*/)";
To recap:
// when the window changes size
window.addEventListener('resize', function () {
var windowWidth = window.innerWidth; // get the new window width
var windowHeight = window.innerHeight; // get the new window height
// use windowWidth and windowHeight here to decide what image to put as a background image
var backgroundImageUrl = ...;
// set the new background image
document.body.style.backgroundImage = "url(" + backgroundImageUrl + ")";
});
I am not sure what browsers you are supposed to be compatible with. This should work in all latest versions of the big browsers.
You may check the window width and change the background depending on the results.
var width = window.innerWidth;
var height = window.innerHeight;
var body = document.body;
if (width <= 1600 && height <= 1000) {
body.style.background = "url(path/to/1600x1000.jpg)";
}
if (width <= 1400 && height <= 900) {
body.style.background = "url(path/to/1400x900.jpg)";
}
// continue as desired
http://jsbin.com/wosaduho/1/
Even better, use some media queries to reduce javascript required.
#media screen and (max-width: 1600px) {
.element {
background: url(path/to/1600x1000.jpg);
}
}
#media screen and (max-width: 1400px) {
.element {
background: url(path/to/1400x900.jpg);
}
}
body {
background-image: url(images/background.jpg);
background-size:cover;/*If you put "contain" it will preserve its intrinsic aspect ratio*/ background-repeat: no-repeat;
}
Try this
You might want to trigger a function like the following on window load and/or on window resize:
function SwapImage(){
var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0),
h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0),
el = document.getElementById('change-my-background');
// use conditionals to decide which image to show
if(w < 1200 && h < 800){
el.style.backgroundImage = "url('img_1200x800.png')";
}
if(w < 900 && h < 600){
el.style.backgroundImage = "url('img_900x600.png')";
}
// etc...
}

window.resize for calculating a box

I have this js code:
$(window).resize(function() {
var formHeight = $(".box-demo").outerHeight() + 40;
$(".box-demo").css("top",-formHeight+"px");
});
When you resize the window. The box-demo is recalculating the height of the form. But now i have a problem with this on mobile devices.
Only when the change width. Then this function must be performed. Now it happened when the document changing the height and width. How can i make this. That is only performed when i changed the width of the document.
Thanks for helping!
There's possibly a better way of doing this, but you could base it on a preset window width value. Only if the width changes should the resizing occur:
var windowWidth;
$(document).ready(function() {
windowWidth = $(window).width();
})
$(window).resize(function() {
if($(this).width() != windowWidth)
{
var formHeight = $(".box-demo").outerHeight() + 40;
$(".box-demo").css("top",-formHeight+"px");
windowWidth = $(this).width();
}
});
Edit: You can also avoid having to append the "px" by using:
$(".box-demo").css({top: -formHeight});
Edit 2: If you want to make it change when only the width has changed, you could also add a height check as well:
var windowHeight;
...
if($(this).width() != windowWidth && $(this).height) == windowHeight)
Extract the the method, and bind it on document ready too.

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