Check onload and onerror using JS/jQuery? - javascript

Using HTML I could manually put this into the body
<img style="display:none;"
onload="Success('test')"
onerror="Fail('test')"
src="http://example.com/test.png"
/>
Is there anyway to do this check using jQuery or JavaScript?
Edit: I want to avoid using HTML and inserting image manually. I am trying to accomplish the check using just jQuery/JS.

Yes.. same thing in jQuery would be this
​$('img').load(function(){ // when loaded successfully
console.log('success');
}).error(function(){ // when theres an error
console.log('error');
});​​​​​
FIDDLE
or
$('img').on({
load: function(){
},
error: function(){
}
})
FIDDLE
EDIT:
If you want it in pure javascript you can do something like this
$('<img/>',{ // <-- create the element
src:'http://wichitaatbat.com/wp-content/uploads/Soccer-Ball.png'
}).load(function(){
console.log('success');
}).error(function(){
console.log('error');
});
http://jsfiddle.net/wirey00/LCkkn/

For error, jquery would work in this fashion:
$('img').on('error', function(e) {
});
Same for load:
$('img').on('load', function(e) {
});

You can do this with pure JavaScript like this:
<script language="JavaScript">
var img = new Image(); // Create new image element
img.onload = function(){
// your code
};
img.onerror = function() {
// your code
};
img.src = 'yourImage.png'; // Set source path
</script>
You can try this approach here.

Related

jQuery .on('load') doesn't work with an object/iframe while .addEventListener('load') does

I'm trying to modify an iframe/object content adding a script into it. At the moment, I have something like this:
// "script" is a node with an self-called function as its content
$(function() {
$('object, iframe').each(function() {
this.addEventListener('load', function() {
this.contentDocument.getElementsByTagName('head')[0].appendChild(script.cloneNode(true));
});
});
});
And it works as expected (the script does its job and it is added to the DOM of the iframe) but the problem comes when I try to do it the "jQuery" way:
// "script" is a node with an self-called function as its content
$(function() {
$('object, iframe').each(function() {
$(this).on('load', function() {
this.contentDocument.getElementsByTagName('head')[0].appendChild(script.cloneNode(true));
});
});
});
In the previous code, the script won't be added to the dom of the iframe.
Is there any reason why the .on('load') version is not working? What can be wrong? Am I missing something?
PS: The iframe is same-origin.
In each case, the inner function's this might not always be what you want it to be. I'd try:
$(function() {
$('object, iframe').each(function () {
$(this).on('load', function (event) {
event.target.contentDocument.getElementsByTagName('head')[0].appendChild(script.cloneNode(true));
});
});
});
Cf. https://api.jquery.com/event.target/

jquery iframe item selector not working

I'm trying to add class to an iframe (on same domain) element but check some of the same issues here and came up with the solution.
The iframe is next to body tag and the js was place before the body end tag.
<script>
$(document).ready(function() {
$('#my-iframe').contents().find('#mnucompany').addClass('is-active');
console.log('ok');
});
</script>
There is no error showing in console except the OK log but the class was not adding to #mnucompany.
What else could be wrong? Any big hints will be appreciated.
After our comments :
You should wait the iframe to be loaded !
$(document).ready(function() {
$('#my-iframe').on('load',function (){
$('#my-iframe').contents().find('#mnucompany').addClass('is-active');
console.log('ok');
});
});
$(document).ready(function() {
var myVar = setTimeout(function () {
var $mnuCompany = $('#my-iframe').contents().find('#mnucompany');
if($mnuCompany.length>0){
$('#my-iframe').contents().find('#mnucompany').addClass('is-active');
console.log('ok');
clearTimeout(myVar);
}
});
}, 1500);

Hide loading gif after ajax callback

I have a simple question but I couldn't find a clean answer. I need to load heavy images after an ajax call and I want to use an animated gif as a pre-loader. I'm using the follow code:
function loadProducts(url) {
$("#loading").show();
$('#inner').fadeOut(1).load(url + ' .product-list', function() {
$('#inner').fadeIn(1000, function() {
$("#loading").hide();
});
});
}
The #loading is hiding when the HTML is loaded .load(url + ' .product-list'. The problem is that the heavy images are still rendering on the screen and I would like to keep showing the animated .gif until the renders of the images are finished. Is there a way to know when the images on the screen are rendered?.
Thanks in advance.
You can use promises to check when all the images have loaded, and then remove the loading gif.
This creates a promise that is resolved when the image has loaded, all the promises are kept in an array, and when all promises are resolved, i.e. all images are loaded, the callback fires.
function loadProducts(url) {
$("#loading").show();
$('#inner').fadeOut(1).load(url + ' .product-list', function() {
var promises = [];
$('#inner').find('img').each(function(_, image) {
var img = new Image(),
def = new $.Deferred();
img.onload = function() {
def.resolve();
}
promises.push( def.promise() );
img.src = image.src;
if (img.complete) img.onload();
});
$.when.apply(undefined, promises).done(function() {
$('#inner').fadeIn(1000, function() {
$("#loading").hide();
});
});
});
}
You can use ImagesLoaded
Sample usage
imagesLoaded( document.querySelector('#container'), function( instance ) {
console.log('all images are loaded');
});
// selector string
imagesLoaded( '#container', function() {...});
// multiple elements
var posts = document.querySelectorAll('.post');
imagesLoaded( posts, function() {...});
Could add/remove the loader as a class? I have base 64encoded the loader, so there is no pre loader required. This also uses a closure to allow the counter to remember its value.
var imgDiv = document.getElementById("imgDiv");
imgDiv.onclick = (function () {
"use strict";
var count = 0; // init the count to 0
return function () {
count++; //count
if (count === 1) { // do something on first click
$('.img-loader-content').addClass('loader');
$('.imgDiv').load("images/img.jpg", function () {
$('.img-loader-content').removeClass('loader');
});
}
if (count > 1) {
$('.imgDiv').slideToggle(400);
}
};
})
();
You may try using Image object. E.g:
function loadImage(url) {
$("#loading").show();
var img = new Image();
img.src = url;
img.onload = function(e) {
$("#loading").hide();
//ur code to append/show the image
};
}
the most approach to this is using onLoad , so basically after the success call of ajax , invoke another call into success function :
http://www.w3schools.com/jsref/event_onload.asp
onload is most often used within the element to execute a
script once a web page has completely loaded all content (including
images, script files, CSS files, etc.).
or use native solution like this :
<img src="w3javascript.gif" onload="loadImage()">
http://www.w3schools.com/jsref/event_img_onload.asp
Also last answer of this question is very useful in your case :
Is there something similar to `$(window).load();` for executing a function after newly inserted Ajax content has finished loading?
You can do it easily by ajaxComplete callback, here check an example http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_ajax_ajaxcomplete

Jquery Preload of big image

How to load the page only when such image is loaded? The base does not work, type:
$('#IDdaImagem').on('load',function(){
})
is a background image, and okay with a jquery plugin to open in other resolutions, the backstretch, it uses a div with class backstretch, as I carry this background image with 2mb before the contents of the site?
i test this and work, but not the item that I give show, appearing at the time, it works only in the alert.
<script>
$('.backstretch img').load(function() {
alert('done loading image');
$("#corpo").show();
});
</script>
Your example makes me think you don't want to "preload" an image necessarily, but want to wait until the image has been loaded before running a script. You can use something like the waitForImages jQuery plug-in for this.
https://github.com/alexanderdickson/waitForImages
Try code given below:
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
// Alternatively you could use:
// (new Image()).src = this;
});
}
// Usage:
preload([
'img/imageName.jpg',
'img/anotherOne.jpg',
'img/blahblahblah.jpg'
]);
With Jquery plugin :
$.fn.preload = function() {
this.each(function(){
$('<img/>')[0].src = this;
});
}
// Usage:
$(['img1.jpg','img2.jpg','img3.jpg']).preload();

Help porting a bit of Prototype JavaScript to jQuery

I have already implemented some AJAX pagination in my Rails app by using the example code for the will_paginate plugin--which is apparently using Prototype.
But if I wanted to switch to using jQuery for future additions, I really don't want to have the Prototype stuff sitting around too (yes, I know it's possible). I haven't written a lick of JavaScript in years, let alone looked into Prototype and jQuery... so I could use some help converting this bit into jQuery-compatible syntax:
document.observe("dom:loaded", function() {
// the element in which we will observe all clicks and capture
// ones originating from pagination links
var container = $(document.body)
if (container) {
var img = new Image
img.src = '/images/spinner.gif'
function createSpinner() {
return new Element('img', { src: img.src, 'class': 'spinner' })
}
container.observe('click', function(e) {
var el = e.element()
if (el.match('.pagination a')) {
el.up('.pagination').insert(createSpinner())
new Ajax.Request(el.href, { method: 'get' })
e.stop()
}
})
}
})
Thanks in advance!
Edit: Nick Craver's answer got me 90% of the way there, so I just had to pick up enough jQuery to make the HTML element substitution. In place of the line where Nick had $.get($(this).attr("href"));, put this line:
$.get(this.href, null, function(data){ $(this).html(data); }, 'html');
You can shorten this down a bit in jQuery to:
$(function() {
$('.pagination a').live('click', function(e) {
$(this).parent('.pagination')
.append("<img src='/images/spinner.gif' class='spinner' />");
$.get($(this).attr("href"));
return false;
});
});
I'm not entirely sure about new Ajax.Request(el.href, { method: 'get' }) though, is this a script being requested? It looks like nothing's being done with the content after return.

Categories

Resources