This question already has answers here:
Get the real width and height of an image with JavaScript? (in Safari/Chrome)
(30 answers)
Closed 9 years ago.
I am scaling images to fit within a div and I want to center them with letterboxes by using positions, but when I try to get the width of the element with .width() immediately after setting the height, .width() returns 0.
For example:
$(image).css("height", "100%");
console.log($(image).width());
This echoes 0 to the console, but if I call $(image).width() from the console sometime later, the correct value is given. How can I get the width of the <img> element immediately after I change it's height?
Edit:
So my code goes something like this:
$(window).load(function(){
cSCMH();
});
function cSCMH()
{
//Some other code
for(var i = 0; i < $("sc mh im img").length; i++)
{
var image = $("sc mh im img")[i];
//More code
$(image).css("height", "100%");
console.log($(image).width());
}
}
The console still receives 0
Edit 2:
Okay so I think I know what the root of the problem is. The images don't appear to load into the page until they are made visible on the screen (I have them in a tab div where the display is set to none onload).
Is there any way to force the images to load even though they are not visible?
I have confirmed this is the issue. The images are not loaded until the div's display is set to block. How can I make the images load in onpageload instead?
Try using the image's load event
function cSCMH() {
$("sc mh im img").load(function () {
var $img = $(this);
$img.css("height", "100%");
console.log($img.width());
}).filter(function () {
return this.complete;
}).trigger('load');
}
Since height() does not provide callback function, You can use animate() here:
$(image).animate({"height": '100%'}, function() {
console.log($(image).width());
})
Also, to make sure all the images are loaded properly, you can wrap your code inside $(window).load(function() { ... });
$(window).load(function() {
$(image).animate({"height": '100%'}, function() {
console.log($(image).width());
})
});
You need to wait for dom change.
$(image).css("height", "100%");
setTimeout(function() {
console.log($(image).width());
}, 0);
setting height in percentage wouldn't set it when you haven't set it's parent's div fixed height. So you can also try by using height 100% to your body like this:
html,body{height: 100%;}
Related
When I load my page and use $('div.logo').width() it returns a massive value of 6500, which is incorrect. The image is only 130 px wide.
But, if I use a setTimeout and check the $('div.logo').width() after a few seconds it returns the correct width.
Why would this be? All of my CSS should be already loaded so why would the few second pause make a difference?
You have to check the image width after the image has been loaded.
So either:
// NOTE: not $(document).ready
$(window).load(function() {
var width = $('.logo img').width();
});
Or
$('.logo img').load(function() {
var width = $(this).width();
});
should give the right width.
Set the width and height attributes to the image. You can specify the size in CSS too. Then the browser will know what size the image will be before it loads.
That's because an image is not loaded yet, so initial size is based on CSS or guessed. You can use:
$('.logo img').load(function() {
var width = $(this).width();
});
Image is getting loaded with GET method,
so you need to check it after,
$('.logo img').load(function(){
//your code
});
If you want your image gets loaded instantly you may go with BASE64 image.
For more detail Plase see here
it can be javascript modifying the layout of page, for example it can be script tags included on the bottom of the page, or any other javascript code executed on JQuery ready or load events. For example if this code appending html code it can affect width of you .logo div.
Another possibility is that your html is incorrect, to check this simply run any HTML validator like this http://www.freeformatter.com/html-validator.html. When taking HTML from your page for validation, be aware that some browsers fix the incorrect HTML, so better get it from your source code.
I want to get selected div width according to following algorithm:
If user resize browser then get div width according to resize browser div.
If user don't resize browser then get div width normally.
Here is my code
jQuery(document).ready(function($) {
if ($(window).resize) {
var width = $('#main_header .wrapper').width($(window).resize);
}
else {
var width = $('#main_header .wrapper').width;
}
});
My code don't work, Please, any one can help me solving this problem. Thanks
This little function will get the width of #main_header .wrapper and update it on resize:
$(function() {
var $wrapper = $('#main_header .wrapper');//the element we want to measure
var wrapperWidth = $wrapper.width();//get its width
$wrapper.text(wrapperWidth);//dunno what you want to do with wrapperWidth but here im setting it as the text of .wrapper just so you can see the value changing
//add resize listener
$(window).resize(function() {
wrapperWidth = $wrapper.width();//re-get the width
$wrapper.text(wrapperWidth);//update the text value
});
});
Here's a working demo: http://jsfiddle.net/5rZ4A/
Your use of if is the problem. Try this:
jQuery(document).ready(function($) {
$(window).resize(function() {
alert("$('#main_header .wrapper').width());
})
});
$(window).resize will always return true because resize is a jQuery function. This code instead watches window for a resize event and calls the inner function when it happens.
I didn’t fill in the inner function because I wasn’t clear on what you wanted to happen upon resize.
I have I div or some other element which I load content into with:
$('#my_div').load('ajax.php',function(){
//Do random stuff.
}
However the height of the div will then change, causing the page to jump up and down, looking ugly.
Is there a way for it to animate the height when the new content is loaded or changed? I know one can do this with FluidMoveBehavior in C#.
How can I achieve the same effect with Javascript/jQuery?
Here's some Fiddle
When you want to create a height or width animation with jQuery you have to set a number indicating the desired size. I assume that you use height: auto in this case so you have to find a little workarround.
Get the height:
var autoHeight = $("#content").height("auto").height();
Animate to autoHeight:
$("#content").animate({height: autoHeight}, 1000);
And together:
var currentHeight = $("#content").height();
var autoHeight = $("#content").height("auto").height();
$("#content").height(currentHeight);
$("#content").animate({height: autoHeight}, 1000);
Stolen from here
What I do is the opposite. I animate the page to scroll to the top if not already BEFORE I call the load.
So that the top of any new dynamic content is always in view.
I know this isn't the answer you were looking for, but I've found it works best.
You could hide #my_div before the load(), and then slideDown() in the complete function:
$('#my_div').hide().load('ajax.php', function() {
$(this).slideDown();
});
Or, create a temporary element, hide it, append it, use its height to animate #my_div once the load is complete, and then remove it.
$('<span/>').hide().appendTo('body').load('ajax.php', function(text) {
$('#my_div').animate({ height: $(this).height() }, '800').html(text);
$(this).remove();
});
I have two sections next to each other, the first with a flexible width image and the second with a series of elements. I want the second to adjust it's height to match the height of the image in the first. I managed to get some javascript working that looks at the height of the image and adjusts the height of second section. However, it only works on resize and I'm unable to get it to work on load as well. For an example, see my fiddle. You'll notice the height matching doesn't kick in until resize.
$(document).ready(function(){
function matchHeight() {
var newHeight = $("#slider").height();
$("#ctas").height(newHeight);
}
jQuery.event.add(window,"resize",matchHeight);
});
http://jsfiddle.net/sGNcc/2/
Just call "matchHeight" in your "ready" handler:
jQuery.event.add(window,"resize",matchHeight);
matchHeight();
Also that's kind-of a weird way to establish an event handler:
$(window).resize(matchHeight);
Call the matchHeight function onload:
$(document).ready(function(){
matchHeight();
});
function matchHeight() {
var newHeight = $("#slider").height();
$("#ctas").height(newHeight);
}
I'm using $('#container_div').load(url) to populate a div via ajax. I would like to animate the height to the height of the returned content but really cant figure out how to achieve this.
I've tried using something like this:
$('#main').fadeOut(function() {
$('#main').load(url, function(data) {
var newHeight = $(data).height();
$('#main').animate({height:newHeight}, function() {$('#main').fadeIn();});
});
});
But can see that this is wrong on so many levels. Especially due to the fact that newHeight === undefined.
Can anybody point me in the right direction here? I would be eternally grateful.
Since fadeOut() finishes by hiding the target elements, chances are your #main will be completely hidden by the time your new data is loaded, rendering any animation of height invisible, and therefore pointless.
But you could just use something like $('#main').show(400) which will animate the element from a size of (0,0) and opacity of 0 to whatever size is allowed by the container and contents and a fully-visible opacity of 1 (and run these animations in parallel, making both of them visible).
But assuming you do care more about animating the height than you do about fading, you still have a problem: by the time load() calls its callback, the height of the target element(s) will already be the height of the content (or as close as possible to it). So animating won't do anything.
I posted a plugin on a previous question that will do what you want, but you'll need to use $.get() instead of load():
$.get(url, function(data) {
$('#main').showHtml(data);
});
...where showHtml is defined as:
// Animates the dimensional changes resulting from altering element contents
// Usage examples:
// $("#myElement").showHtml("new HTML contents");
// $("div").showHtml("new HTML contents", 400);
// $(".className").showHtml("new HTML contents", 400,
// function() {/* on completion */});
(function($)
{
$.fn.showHtml = function(html, speed, callback)
{
return this.each(function()
{
// The element to be modified
var el = $(this);
// Preserve the original values of width and height - they'll need
// to be modified during the animation, but can be restored once
// the animation has completed.
var finish = {width: this.style.width, height: this.style.height};
// The original width and height represented as pixel values.
// These will only be the same as `finish` if this element had its
// dimensions specified explicitly and in pixels. Of course, if that
// was done then this entire routine is pointless, as the dimensions
// won't change when the content is changed.
var cur = {width: el.width()+'px', height: el.height()+'px'};
// Modify the element's contents. Element will resize.
el.html(html);
// Capture the final dimensions of the element
// (with initial style settings still in effect)
var next = {width: el.width()+'px', height: el.height()+'px'};
el .css(cur) // restore initial dimensions
.animate(next, speed, function() // animate to final dimensions
{
el.css(finish); // restore initial style settings
if ( $.isFunction(callback) ) callback();
});
});
};
})(jQuery);
It's because $(data) isn't in the DOM, however $(this) is :)
$('#main').fadeOut(function() {
$('#main').load(url, function(data) {
var newHeight = $(this).height();
$(this).animate({height:newHeight}, function() {$(this).fadeIn();});
});
});
However the new height will already be what it's doing to be at this point, and you can't guess the height of the new content because it's all determined by it's container, you may be better off storing and restoring it, something like this:
$('#main').animate({ opacity: 0 }, function() {
var height = $(this).height(); //previous height
$('#main').load(url, function(data) {
var newHeight = $(this).height(); //new height
$(this).height(height) //set old height before animating to new
.animate({height:newHeight})//animate to new height
.fadeIn(); //fade is a queued animation
});
});
I'm animating the opacity here so the display:none doesn't get applies, making this much simpler overall.
First, load your data into a temporary div, which you have hidden way to the left and the top of the page with absolute positioning. You can then get the height of that (as long at it's height in the css is set to 'auto'. Use that height information to animate the div you are showing. Finally, don't forget to remove the temporary div from the dom and set the height of the div you show to 'auto' once the animation is complete.