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.
Related
I have made a little plugin where I get the size using naturalHeight and naturalWidth
Sometimes when loading page I get 0 in width and height (other times it works fine).
I guess it is because it calculate the size before loading the image.
How can I correct this?
I have tried to run plugin $("selector").myplugin() inside $(document).ready, but that doesn't change anything
I have also tried to wrap setTimeout around the variables where I am using naturalHeight and naturalWidth, but that doesn't prevent rest of the code to run - and I won't make it slower loading than necessary (wrap everything in setTimeout if not necessary)
So my question - are there a way to
if size is 0 - wait a little and try again
Not continue running rest until it is not 0 anymore
Or does anyone have another solution?
Ready wait only for dom to be loaded , You can use the load() on your image in order in this case , you'll not wait till all the window elm are loaded
See below snippet after loading image , The size of this last is being printed on the bottom ,
$(function(){
$( "#img" ).load(function() {
console.log($(this).width()+"-"+$(this).height())
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="img" src="https://cdn.pixabay.com/photo/2017/09/07/14/15/wide-2725426_960_720.jpg" >
As of Jquery 1.8 a change was made when getting the height() of an element. I have a CSS div height set to auto with the image inside dictating the height and width of the div by using % and auto), and when the window loads i use Jquery to get the height of the element and make another div next to it the same height. After researching this I have noticed that it is returning the height before the CSS has set the new height that is set by the image. 1.7 allowed this, but 1.8 and up does not. Is ther a work around.
this is the css
#element1{ width:80%; height:auto;}
#element1 img{width:100%; height:auto};//this allows the image to resize with the page responsively.
jQuery...
$(window).ready(
function(){
var x = $("#element").height();
alert(x); // this would return what the height was dynamically set as by the css in 1.7, but 1.8 returns a small number that i am pretty certain is just the padding added to 0px
});
Hopefully this makes sense, and someone has a work around.
Thanks
Instead of listening on $(window).load(), which might stall proper height assignment until all resources have been successfully loaded, you can listen to successful loading on each <img> instance and trigger proper height calculation.
However since in your question you only have one element you are concerned with setting height dynamically, I have reduced my script without the need to loop through all <img> instances on the page. Assuming that you have the following markup:
<div id="element1">
<img ... />
</div>
You can create a new image, check if it is loaded and then instruct jQuery to run the height calculations and set a new height when this is done:
$(function() {
var $img = $('<img />', {
'src': $('#element1 img').attr('src')
});
$img.load(function() {
$('#element2').css('height', $('#element1').height());
});
});
There's a mismatch between your css selector (#element1) and your jquery selector ('#element'). Start by making them both match whatever you have on your html element. You could also wrap this in a timeout so your image will have time to fully load.
$( document ).ready(function() {
setTimeout(function() {
$('#element2').height( $('#element1').height() );
}, 2000});
});
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);
}
Is it possible to load a background-image asynchronously?
I've seen many jQuery plugins to load normal image in an asynchronous way, but I can't find if it's possible to preload / asynchronously load a background-image.
EDIT
I clarify my problem. I've been working on this test site http://mentalfaps.com/
The background image is loaded randomly from a set of images refreshed each hour by a chron job (which takes random images on a flickr catalog).
The host is free and slow at the moment, so the background image takes some time to load.
The positioning of the first overlay (the one with the PNG transparent mentalfaps logo) and width are regulated by a function created in the jQuery(document).ready construct.
If you try to refresh the page many times, the width of the right overlay div is 0 (and so you see a "hole" in the layout)
Here is the method to set my positions:
function setPositions(){
var oH = $('#overlay-header');
var overlayHeaderOffset = oH.offset();
var overlayRightWidth = $(window).width() - (overlayHeaderOffset.left + oH.width());
if (overlayRightWidth >= 0) {
$('#overlay-right').width(overlayRightWidth);
} else {
$('#overlay-right').width(0);
}
var lW = $('#loader-wrapper');
lW.offset({
left: (overlayHeaderOffset.left + oH.width() - lW.width())
});
}
The problem is that the $(window).width() is lower then the effective window width! so the check fails and the script goes for $('#overlay-right').width(0);
any ideas?
Not sure whether I really understand your question, but background images (and all other images) are already loaded asynchronously - the browser will start separate requests for them as soon as it encounters the URL while parsing the HTML.
See this excellent answer for background on loading order: Load and execution sequence of a web page?
If you meant something else, please clarify.
The trick to loading something in the background is to load it once, so the next time when it is loaded it already is in the cache.
Put the following at the end of your html:
<script>
var img = new Image();
img.onload = function () {
document.getElementsByTagName('body')[0].style.backgroundImage = 'background.png';
};
img.src = 'background.png';
</script>
You could use a prefetch link in the head.
<link rel="prefetch" href="/images/background.jpg">
You should be able to add these links to the head via JavaScript.
I like to use CSS to fill the background with a color for page load.
After DOM ready event, I use jQuery to modify the CSS and add a background image. That way, the image isn't loaded until after page loads. Not sure about async, but this method gives the user a decent experience.
Example: http://it.highpoint.edu/
The right side navigation links have a background image. The page initializes with a background color. It is replaced with a background image after page load, via jQuery.
changes in this file jquery.ImageOverlay.js
set your height and width and enjoy this...
imageContainer.css({
width : "299px",
height : "138px",
borderColor : hrefOpts.border_color
});
As it is already mentioned, the background image is loaded asynchronously. If you need to load the background image from JQuery code you may also set the addClass() method to set a CSS class or attr("style=\"background-image:url('myimage.png')\"")
Ive found the answer myself, it was a problem due to the .offset() method that gived sometimes the wrong values.
I had the write values using the .position() :
var overlayHeaderOffset = oH.position();
Here's what i have so far:
function loadOff(){
$(document).ready(function(){
$("#eLoader").ajaxStop(function(){
$(this).hide();
$("#eventsContent").show();
var h = document.body.scrollHeight;
$("#bodyBackground").css("height",h+100+"px");
$("#sidePanel1").css("height",h-105+100+"px");
$("#bottom").css("top",h+100+"px");
});
});
}
This is a callback function for a JQuery ajax function, basically what is does is when all ajax is finished .ajaxStop() it hides the loader then shows the content.
The problem i am having is adjusting bodyBackground, sidePanel, and bottom to fit the content. I dont care to have it elastic and retract for short content at this point, i would just like it to extend to proper positioning based on content length.
All divs are absolutely positioned. The numbers in the function are broken down simply to make it easy to explain. -105 is the offsetTop of that element and +100 is the margin between the end of the content and the elements.
if there is a better, more efficient way to achieve this outcome, please, do tell.
Thanks.
Based on your code, the only thing you ought to see is the top 105px of #sidePanel1. Is that your intent? (h = the bottom of the window, according to your code.)
Sticking with the JQuery patterns, you would use
var h = $(window).height();
Maybe you're looking for this instead of the browser window's height? It will get the height of the content element.
$("#eventsContent").outerHeight();