Getting image height on document load - javascript

I want to set div#top height equals image height. I wrote:
$(document).ready(function() {
setTopHeight();
});
/*
* window resizing
*/
$(window).resize(function() {
setTopHeight();
});
/*
* setting #top height by banner height
*/
var setTopHeight = function() {
var bannerHeight = $('#banner-image').height();
$('#top').height(bannerHeight + 'px');
};
It works on resize, but doesn't at reload. I've tried sth like this:
$(document).ready(function() {
setTimeout(function() {
setTopHeight();
}, 50);
});
and it works, but of course it's not solution. Can somebody tell me why console.log returns 0?
$(document).ready(function() {
console.log($('#banner-image').height());
});

.ready won't work because your image has not been loaded yet. use .load

$(document).ready fires when the DOM is ready, but the image might still be downloading - so no height yet. You might use jQuery load on the image.
$('#banner-image').on('load', function () {
setTopHeight();
})

The jQuery .load() acts as an event handler. .load() is a shortcut for .on('load, function(){}). It will be triggered once the image/element if fully loaded.
Example 1:
$('#banner-image').load(setTopHeight);
Example 2
$('#banner-image').load(function(){
setTopHeight();
});
Example 3
$('#banner-image').on('load', setTopHeight);

Try .load() instead .ready()
$(window).load(function() {
setTopHeight();
});

The image load is in a second HTTP round after your document. so you need listen to image load
$('#banner-image').load(setTopHeight);

Related

How to make script rerun on window resize?

I think the question is pretty much self explanatory...
I've got a script that is drawing some graphics across the window. Currently, if I resize the window (like taking it full screen) the script continues to affect only the windows' initial size. It should rerun, responding to the new dimensions.
I've tried adding this to my script.
$(window).resize(function() {
});
It did run whenever I resized it... but ONLY when I resized it! No more on load... as it also should.
I think I'm on the right path, but what am I missing?
Codepen here.
drawingFunction function(){
// your drawling code;
}
$(window).resize(function() {
console.log('window is resized');
drawingFunction();
});
$( document ).ready(function() {
drawingFunction(); // for onload
});
function drawStuff() {
// move here the drawing code ............
};
// call it where the loading process is
drawStuff();
// call it on resize , too
$(window).resize(function() {
drawStuff();
});
To call on loading
If you are using jQuery:
$(function(){
drawStuff();
})
if not, try this.
window.onload = function(){
drawStuff();
}
All is ok, but when I maximize or restore window, resize event is fired 2 times. When I press F11 in Firefox to go fullscreen, browser's toolbar is sliding up slowly and resize event is fired up to 40 times. My proposal is to use delay:
var timeout;
$(window).resize(function() {
clearTimeout(timeout);
timeout = setTimeout(onResizeOnly, 500);
});
function onResizeOnly()
{
//your code here
}
In the tag :
<body onresize="drawStuff()">
IMHO, it's the easiest way.

Attach jquery call to image load

I am attempting to incorporate a script (written by "dystroy" I believe) that centers an image vertically within a div with the overflow hidden. It works quite well but many of my images are dynamically loaded upon mouseover.
I need to find a way to call the script upon image load. It's been two days now and as JS/JQuery aren't my native language, I find my self here.
Can anyone suggest how I might get the following to fire on image load?
Many thanks!
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$('.container').each(function () {
var $img = $(this).find('img');
$(this).scrollTop(($img.height() - $(this).height()) / 2);
$(this).scrollLeft(($img.width() - $(this).width()) / 2);
});
});
//]]></script>
$(document).ready(... Will wait until everything on the page is loaded (including the images) before executing the function.
<script type='text/javascript'>//<![CDATA[
$(document).ready(function(){
$('.container').each(function () {
var $img = $(this).find('img');
$(this).scrollTop(($img.height() - $(this).height()) / 2);
$(this).scrollLeft(($img.width() - $(this).width()) / 2);
});
});
//]]></script>
Perhaps you could combine the load api (https://api.jquery.com/load/):
$("#book").load(function() {
// Handler for .load() called.
});
with the event delegation to make it so that any new images loading inside one of your specified divs get an onload function applied to them (https://learn.jquery.com/events/event-delegation/):
// attach a delegated event
$("#list").on("click", "a", function(event) {
event.preventDefault();
console.log($(this).text());
});

Can someone please tell me why this js function doesn't run on load?

I've:
//Resize tabs - height when window size changes. Don't forget to reset niceScroll
function recalc_tab_height () {
//
var wrapper_h = $(".ui-panel-content-wrap").outerHeight();
var content_h = $(".ui-content").outerHeight();
var current_h = $(".tab1").outerHeight();
var newHeight = (wrapper_h - content_h) + current_h;
//
$(".tab1, .tab2, .tab3").css({"height":newHeight}).getNiceScroll().resize();
}
//Run once onLoad
recalc_tab_height();
That is supposed to resize lyrics section on-load to fit the screen. But it doesn't run at all... any ideas why? it is inside ui.js
http://mac.idev.ge:800/mobile-radio/
try
$(function() {
recalc_tab_height();
});
instead of your last line.
$(...) is a shortcut for $(document).ready(...) and is executed as soon as your page is entirely loaded, so that you can deal with DOM element properties.
Try this : Need to set $(document).ready
$(document).ready(function(){
//Run once onLoad
recalc_tab_height();
});
To load this function either you should use this on body as
<body onload="recalc_tab_height();" >
or by jquery
$(document).ready(function() {
recalc_tab_height();
});
Wrap the function call when the dom is ready.Try like this
$(document).ready(function(){
recalc_tab_height();
});
A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $(document).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $(window).load(function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready.
So you have to call your function inside
$(document).ready({...}); or $(window).load(function() { ... });
I changed css() to animate() and it works.

FlexSlider: How to get image height on page load using JS or jQuery?

Using FlexSlider on my site, I'm trying to get the height of the first image in the slider. I thought the following code would do the job, but it seems like the images are loaded very late, so that they have no height on this jQuery event. The code will return "0".
$(window).load(function() {
$(document).ready(function() {
var height = $(".flexslider>div>ul>li.flex-active-slide>a>img").height();
console.log(height);
});
});
But if I run this code in my browser console after the page has loaded, the correct height is returned.
How can I get the image height on page load/ready using jQuery or JavaScript?
Thanks for clarifying that the window.load event occurs after document.ready, even though this had nothing to do with the actual problem.
The reason why the code returned "0", was due to a css-class in the default flexslider.css:
.flexslider .slides > li {display: none; -webkit-backface-visibility: hidden;} /* Hide the slides before the JS is loaded. Avoids image jumping */
The solution was to wait until the slider had loaded properly, by using the callback API:
$(window).load(function() {
$(".flexslider").flexslider({
start: function() {
var height = $(".flexslider a>img").first().height();
console.log(height);
}
});
});
The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content (e.g. images) also has been loaded.
The onload event is a standard event in the DOM, while the ready event is specific to jQuery. The purpose of the ready event is that it should occur as early as possible after the document has loaded, so that code that adds funcionality to the elements in the page doesn't have to wait for all content to load.
See window.onload vs $(document).ready()
$(document).ready(function() {
console.log($('.flexslider > ul > li > a > img').height());
});
See DEMO http://jsfiddle.net/ducwidget/cufsn/1/

How to run a jQuery Code after loading all the images in my page?

How to run a jQuery Code after loading all the images in my page ?
$(window).load(function(){})
Checking to see that all images have loaded is slightly involved, so unless you have a pressing need to be so precise, it is much easier to check that all image and everything else has loaded:
$(window).load(function() { ... });
This makes use of the jQuery .load() method.
If you do really need to check for specifically only images, then things get a little trickier. I initially wanted to do this:
$("img").load(function() { ... }); \\ THIS IS INCORRECT!!!!!
However the above creates a jQuery object that contains all images, and then it binds function() { ... } to each of these images. So the above will trigger a function as many times as there are images on the page!
To get around this, we should check how many images there are on the page, and only fire the function once after all those images have been loaded:
$(function() {
// To keep track of how many images have loaded
var loaded = 0;
// Let's retrieve how many images there are
var numImages = $("img").length;
// Let's bind a function to the loading of EACH image
$("img").load(function() {
// One more image has loaded
++loaded;
// Only if ALL the images have loaded
if (loaded === numImages) {
// This will be executed ONCE after all images are loaded.
function() { ... }
}
});
});
jsFiddle example
$(function() {
var length = $('img').length ;
var counter = 0;
$('img').each(function() {
$(this).load(function(){
counter++;
if(counter == length) {
Callback(); //do stuff
}
});
});
});
I did something like this recently, but went about it differently.
$('img').on('load', function(){
$('img').off('load'); //detaches from load event, so code below only executes once
// my code to execute
});
Not a direct answer. Still worth referring.
Refer
Run JavaScript Only After Entire Page Has Loaded
jQuery callback on image load (even when the image is cached)
Code
$(window).bind("load", function() {
// code here
});
#Peter Ajtai answer will work except on IE's cached images. To make it work with IE, here's a solution: https://stackoverflow.com/a/3877079 or by using the imagesLoaded plugin.
For anyone using jquery this little snippet does the trick (it ensures that all images are loaded before any script inside it are run)...
$(window).bind("load", function() {
// code goes here here
});

Categories

Resources