I'm using this lazy load jQuery script ( http://www.appelsiini.net/projects/lazyload ) to lazy load images when they appear in the viewport, but I want to run some javascript / styling to style the new, full image that is loaded.
How can I run javascript once the image has been loaded?
The jQuery Lazy Load plugin has a callback parameter called
appear, that gets triggered for every image, once it's been loaded. Use it like this, in this case e.g. to put a red border on the image, once it's loaded (this in the callback refers the raw DOM img object):
$(document).ready(function () {
$("img").lazyload({
appear: function () {
//Image is loaded. Put javascript here.
this.style = "border: 1px solid red";
}
});
});
Although I will say, if you wanna add styling to the image, you should use css instead. But there might be cases where you actually wanna trigger javascript on image-load, and this seems like the way to do it with the lazy load plugin :)
Bind a handler to the image load event. But be aware that you have to set the handler fore every image, as the load event doesn't bubble up the DOM tree. Here is a way:
$('#img').on('load', function() {
//do some styling...
});
However, my experience tells me that, with this event it's better if you use the onclick attribute. It my happen that, when you set the handler via jQuery, some images have already loaded.
Related
I am trying to obtain an element width using the following code just before the </body>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
var diff = $('div.canvas img.photo').get(1).width;
console.log(diff);
});
</script>
but it logs undefined. However, if I run $('div.canvas img.photo').get(1).width directly in the Chrome/Firebug console, it returns the correct width. The image is not being loaded with Javascript, so should be in place when the document ready fires. What am I doing wrong?
No, it shouldn't. document.ready fires when all HTML has been loaded, but not the images. If you want to wait until all images are loaded, use window.load.
Example:
$(window).load(function(){
var diff = $('div.canvas img.photo').get(1).width;
console.log(diff);
});
Also, as some people have pointed out, you were attempting to get the property ".width" twice.
If at all possible, set a width on the imagetags in CSS. That way, you can safely use document.ready for your code. Using window.load will naturally delay the execution of your script, could be a second, could be ten, depending on the speed of the clients connection, and the amount of content on your page. This could cause unwanted jumps and jitters if you're performing any styling.
img isn't being loaded on DOM ready. docs:
While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.
change to this:
$(window).load(function(){
var diff = $('div.canvas img.photo').get(1).width;
console.log(diff.width);
});
Image's width would only be available when its loaded completely.
jQuery supports onload event on every images too.
You can use,
$('div.canvas img.photo').load(function(){
// here the image (or all images which match selector) has been loaded.
}
The problem is that your image is not loaded yet when you try to get its dimentions. To make it work wrap your code into $(window).load. Or another option. If you know the sizes of the image you can provide width and height attributes, then it's going to work even inside DOMContentLoaded. Sometimes it's preferable because onload event takes longer to fire then 'DOMContentLoaded'.
Otherwise you would need to use $(window).load, see #Andreas Carlbom answer.
I’m using jQuery for my project. $(function(){...}) fires the function “when the DOM is ready” — this doesn’t say that all images are loaded, right?
Is there an event that gets fired when every image is loaded too?
I guess you mean
http://api.jquery.com/ready/
versus
http://api.jquery.com/load-event/
Example: Run a function when the page is fully loaded including graphics.
$(window).load(function () {
// run code
});
without jQuery:
window.onload=function() {
alert(document.images.length);
}
You can check on load event of image tag. This will get fired when image loading completes.
$("img").load(function(){
// your code
});
window.onload will solve this, I wrote about this there: http://amrelgarhy.com/blog/how-to-tell-when-images-have-loaded/
I have a slight problem.
I need to show some safety information in a JS drawer that the page loads with open. The images creating the drawer are kind of hefty and as such the safety text in the drawer render prior to the background, creating a really ugly loading experiance. Is there a easy way I can say
DO NOT LOAD safetyText UNTIL safetyBG is loaded ?
We're not using any libraries (i.e. jQuery) so a JS solution would have to work as a script by itself.
If I understand you correctly, you only want to display safetyText once safetyBG has fully loaded. To achieve that, hide safetyText, then check on document.onload if safetyBG has loaded. If so, show text, if not, attach function to show text to safetyBG.onload:
function showSafetyText() {
//show text
}
window.onload = function() {
var safetyBG = document.getElementById("safetyBG"); // tweak as necessary
//have to check to see if img loaded, if you would simply assign showSafetyText
//to img.onload, it would never run if the img was fully loaded already
if (!safetyBG.complete) {
safetyBG.onload = showSafetyText;
} else {
showSafetyText();
}
}
You mentioned images (rather than a single image) in your post. If that's the case you'll want to write a function that loops through the images to check to see if they've all loaded (at which time you can load the text); then attach this function to each of the images' onload events (unless all images are loaded already in which case you can simply show the text).
I'm loading image tags via AJAX and inserting them with the conventional .html(content) function in jQuery alongside a bunch of other HTML. However, this question still applies if you're loading a page from scratch. Now, I have a background image placeholder to be put there while the image loads. I want this background image to go away when the image loads.
Problem:
If I attach a conventional .load(function) event listener, I am concerned that the image might load before the hook is applied (putting the hook in a small JS <script> right after the image instead of in a $(function(){}) block might help a bit). I have yet to encounter such behaviour, but I know of nothing in the specification that prevents this from happening (since the image tag ought to be fully parsed before the hook is applied).
My current solution. Put the command in an inline onload= property within the image tag.
Is there a better way?
Up until a week or so ago I would have been lost too. Thankfully this answer to another question will help you out:
Basically put this in $():
$(function(){
var img = $("#idofimage").load(function () {
/* your magic to swap out placeholder */
});
if (img[0].complete) {
// Trigger the load handler if the image
// is already loaded
img.trigger('load');
}
});
You don't need jQuery for this, you can do it with CSS.
.my-img-loader-class { background:url('placeholder-or-progress'); }
Or if you don't want to change your HTML:
#container img { background:url('placeholder-or-progress'); }
To show placeholders while images are loading in a specific div.
The way it works is the image element will show the placeholder image as its background, and when the src loads it will appear above the placeholder, so as to replace it nicely.
I'm working on a client project and I have to include their header and footer, which includes some core JavaScript files. I have a couple of PNGs on the page, but their core JS file is poorly coded and doesn't check for IE 7 before attempting to replace IMG tags that contain .png files with DIVS that use the AlphaImageLoader filter. The result is that in IE 7, all my .png images are replaced with DIV tags that have a default display: block, causing a linebreak after every single png image in my pages.
What I'd like to do is override their function with a better one or somehow prevent theirs from executing, but I cannot modify the JS file itself, which both defines the function and attaches it to the window onload event. I've tried redefining the function under the same name in several places (header, just before the /body tag, in $(document).ready, etc...) but the original function always seems to execute, presumably because the original function code is what is stored with the event handler, and not merely a pointer to the function.
Any way I can fix? Is there a way to selectively remove onload event handlers?
If that's the only thing running at load, I think you could do
window.onload = null;
If there are other things running, I guess you'd have to reattach them. It's a little fragile, I suppose.
In IE7 you can use the detachEvent method:-
window.detachEvent("load", fn)
where fn is the function that was attached, however since there is jquery in this mix it may be a tall order getting hold of the actual function that was attached. Most likely the actual function attached will be anonymous.
A large IFRAME between header & footer should do the trick.
Well, depending on how it was bound, you might be able to get away with something like:
window.onload = function(){
var alert=function(a){
console.log(a);
}
window.onload();
}
Obviously, you'd want to redefine something other than alert, but that might work.
maybe if that's all it does, you can write a function to reverse it, look for all png images and strip away the div, and if you want to skip certain images you can implant an attribute to those you want to treat differently
another way is to trick the function by not having the png part of the image file name, and on load, append the .png (after their onload)
or maybe you can replace your png images with another tag, and replace onload
by the way, you can know exactly whats inside the onload, if you just alert window.onload, if there is nothing but that functionality, set window.onload = null;
Have you tried using $(window).unbind("load")?
Do you know the name of the function that replaces the PNG images? If so you might be able to override the existing function by doing something like this:
// Assuming PNG function is called pngSwap
function pngSwap() {
alert('png swap');
}
$(document).ready(function() {
if (window.pngSwap && window.pngSwap.constructor === Function) {
var oldFunc = window.pngSwap;
window.pngSwap = function() {
alert('new png swap');
}
}
pngSwap();
});