I am using blazy image loader and I am trying to get the data src from the element on error. Basically if the image is not found or invalid I want to change the last 4 letters of the image src, but I cannot figure out how to get the actual source. Here is my code:
var bLazy = new Blazy({
loadInvisible: true,
error: function (ele, msg) {
if (msg === 'missing') {
var dsrc = ele.src();
var fallback = dsrc.replace('y.jpg','b.jpg');
ele.src(fallback);
} else if (msg === 'invalid') {
console.log(this);
}
},
success: function(ele,msg){
//console.log(ele.parseJSON());
console.log(this);
}
});
I also tried ele.attr('data-src'); and that didn't work either. When I look at the console for console.log(ele) I get the actual image not the element.
Anyone who could help... please!!
If you would like to get the "src" attribute, you can use the $(ele).data("src") or $(ele).attr("data-src") with JQuery.
After you can modify.
;(function() {
// Initialize
var bLazy = new Blazy({
error: function(ele, msg){
if(msg === 'missing'){
// Data-src is missing
console.log(msg);
} else if(msg === 'invalid'){
// Data-src is invalid
//console.log( $(ele).data("src") );
var src = $(ele).data("src");
src = src.substring(0, src.length - 4) + 'b.jpg';
//or
//src = src.replace('y.jpg','b.jpg');
$(ele).attr("src",src);
}
}
});
})();
Related
I am trying to create a function that will recursively try to reload an image until it either is successful, or a maximum amount of attempts is reached. I have created this function, but it doesn't work (is it due to the fact that the reference to the image has changed?):
function reload (image, URL, maxAttempts)
{
image.onerror = image.onabort = null;
if (maxAttempts > 0)
{
var newImg = new Image ();
newImg.src = URL;
newImg.onerror = image.onabort = reload (image, URL, maxAttempts - 1);
newImg.onload = function () {
newImg.onerror = newImg.onabort = null;
image = newImg;
}
}
else
{
alert ("Error loading image " + URL); /* DEBUG */
}
}
Which is used in the following manner:
var globalTestImage = new Image ();
reload (globalTestImage, "testIMG.jpg", 4);
Rather than it attempting to load "testIMG.jpg" four times, and waiting in between attempts, it instead tries to load it twice, and regardless of whether it was successful the second time around it will display the error message.
What am I doing there? More precisely, why is it acting the way it is, rather than retrying to load the image 4 times?
(function ($) {
var retries = 5; //<--retries
$( document).ready(function(){
$('img').one('error', function() {
var $image = $(this);
$image.attr('alt', 'Still didn\'t load');
if (typeof $image !== 'undefined') {
if (typeof $image.attr('src') !== 'undefined') {
$image.attr('src', retryToLoadImage($image));
}
}
});
});
function retryToLoadImage($img) {
var $newImg = $('<img>');
var $src = ($img.attr('src')) || '';
$newImg.attr('src', $src);
$newImg.one('error', function() {
window.setTimeout(function(){
if (retries > 0) {
retries--;
retryToLoadImage($newImg);
}
}, 1000); //<-retry interval
});
$newImg.one('load', function() {
return $newImg.attr('src');
});
}
})(jQuery);
Some code I wrote for the same case a while ago. Hope it helps you!
In the end I solve this issue in a simple (if inelegant) way:
try
{
canvas.getContext("2d").drawImage (testImage, 0, 0);
backgroundLoaded = true;
}
catch (err)
{
testImage = new Image ();
testImage.src = "placeholder.jpg";
}
The idea is that if an image failed to load, it will fail when rendering it on the canvas, producing an error. When such an error happens, we can create a new image and try again.
I try to copy paste the code from Mozilla's getting started with Javascript tutorial
var myImage = document.querySelector('img');
myImage.onclick = function() {
var mySrc = myImage.getAttribute('src');
if(mySrc === 'images/firefox-icon.png') {
myImage.setAttribute ('src','images/firefox2.png');
} else {
myImage.setAttribute ('src','images/firefox-icon.png');
}
}
I am getting an error "Cannot set property 'onclick' of null". How can correct the code?
I am just getting started with javascript. please forgive me if it is a silly mistake from my part.
You might be trying to assign the click handler before the element has been rendered so the query selector will not find the img tag. Try executing your script after the page has rendered like so
window.onload = function () {
var myImage = document.querySelector('img');
myImage.onclick = function() {
var mySrc = myImage.getAttribute('src');
if(mySrc === 'images/firefox-icon.png') {
myImage.setAttribute ('src','images/firefox2.png');
} else {
myImage.setAttribute ('src','images/firefox-icon.png');
}
}
}
This question already has answers here:
'console' is undefined error for Internet Explorer
(21 answers)
Closed 8 years ago.
Hi i found the problem in other stackoverflow questions , the problem is i have tried all solutions that should work, but i think im not understanding where and how to implement that fixes..
My problem is console.log in internet explorer throws an error as undefined. I search and found
Console undefined issue in IE8
Internet Explorer: "console is not defined" Error
I try to wrap the code inside the function using a condition like 'if(window.console) '
this dosent work i even try most of the recommended contitions no one work, try to insert the snnipet in the code so it worked, but it dont..
Im obviously not understanding how and where to put does fixes. Sorry for my ignorance. but im in a hurry, need to someone points at my stupidity
Thanks
var jcount = 0;
var scroll_count = 0;
var playflag=1;
var ajxcallimiter=0;
var hp_totalcount=parseInt($("#hp_totalcount").val());
if(hp_totalcount<5)
hp_totalcount=5;
function hlist_slider()
{
if($(".items img").eq(jcount).length != 0 && playflag==1){
firedstyle();
console.log(jcount);
$(".items img").eq(jcount).trigger("mouseover");
if(jcount % 5 === 0 && jcount!=0)
{
console.log('scroll');
api.next();
scroll_count++;
}
jcount++; // add to the counter
if(jcount>hp_totalcount)
{
if(playflag==1)
{
jcount = 0; //reset counter
while(scroll_count--)
{
api.prev();
}scroll_count=1;
}
}
}
else if(jcount<hp_totalcount && playflag==1)
{
playflag=0;homepagelist_nextclick();playflag=1;
}
else
{
if(playflag==1)
{
jcount = 0; //reset counter
while(scroll_count--)
{
api.prev();
}
scroll_count=1;
}
}
}
$(function() {
var root = $(".scrollable").scrollable({circular: false}).autoscroll({ autoplay: true });
hlist_slider();
setInterval(hlist_slider,10000);
// provide scrollable API for the action buttons
window.api = root.data("scrollable");
});
function firedstyle()
{
$(".items img").on("hover",function() {
// see if same thumb is being clicked
if ($(this).hasClass("active")) { return; }
// calclulate large image's URL based on the thumbnail URL (flickr specific)
var url = $(this).attr("src").replace("t_", "");
var tbtit = $(this).siblings('.tbtit').text();
var tbdesc = $(this).siblings('.tbdescp').text();
var tbtitgoto = $(this).attr("data");
// get handle to element that wraps the image and make it semi-transparent
var wrap = $("#image_wrap").stop(true, true).fadeTo("medium", 0.5);
// the large image from www.flickr.com
var img = new Image();
// call this function after it's loaded
img.onload = function() {
// make wrapper fully visible
wrap.fadeTo("fast", 1);
// change the image
wrap.find("img").attr("src", url);
wrap.find(".img-info h4").text(tbtit);
wrap.find(".img-info p").text( tbdesc);
wrap.find("a").attr("href", tbtitgoto);
};
// begin loading the image from www.flickr.com
img.src = url;
// activate item
$(".items img").removeClass("active");
$(this).addClass("active");
// when page loads simulate a "click" on the first image
}).filter(":first").trigger("mouseover");
}
function toggle(el){
if(el.className!="play")
{
playflag=0;
el.className="play";
el.src='images/play.png';
//api.pause();
}
else if(el.className=="play")
{
playflag=1;
el.className="pause";
el.src='images/pause.png';
// api.play();
}
return false;
}
function hp_nxtclick()
{
homepagelist_nextclick();
console.log('scroll');
if(api.next()){
scroll_count++;}
}
function homepagelist_nextclick()
{
var hp_totalcount=parseInt($("#hp_totalcount").val());
var hp_count=parseInt($("#hp_count").val());
if(hp_totalcount==0 || hp_count >=hp_totalcount)
return ;
if(ajxcallimiter==1)
return;
else
ajxcallimiter=1;
$.ajax(
{
type: "GET",
url: "<?php echo $makeurl."index/homepageslide/";?>"+hp_count,
success: function(msg)
{
hp_count=parseInt($("#hp_count").val())+parseInt(5);
$("#hp_count").val(hp_count);
$("#hp_list").append(msg);ajxcallimiter=0;
}
});
}
The problem is that the console (developer tool panel) needs to be active on page-load*.
Hit F12, reload your page, and you should get what you're looking for.
*Just to clarify: The developer panel needs to be open prior to window.console being called/tested. I'm assuming your code is being run on-load.
This should work:
if(!window.console || !window.console.log) window.console = {log: function(){}};
This way you will be able to use console.log without producing errors.
In my code, I put this snippet at the top - before any other javascript that might try to use the console loads:
if (window.console == null) {
window.console = {
log: function() {},
warn: function() {},
info: function() {},
error: function() {}
};
}
Or in coffeescript:
if not window.console?
window.console = {
log: () ->
warn: () ->
info: () ->
error: () ->
}
This provides a dummy console for browsers that don't include one.
I have a image loader function, that calls a function when all images are loaded, regardless how many I load. But currently it fails when a image src file name is not valid, because onload is not called.
How can I throw an error message, if an image is not loaded?
loadImage: function(image, id, fn) {
var bgImg = new Image(),
self = this;
// counting images currently loaded
this._loadingImages++;
// set image source and onload callback
bgImg.src = image;
bgImg.onload = function() {
fn(image, id);
self._loadingImages--;
if( self._loadingImages === 0 ) self.imagesLoaded();
}
},
loadImage: function (image, id, fn) {
var bgImg = new Image(),
self = this;
// counting images currently loaded
this._loadingImages++;
// set image source and onload callback
bgImg.src = image;
bgImg.onerror = function () {
// your error code
}
bgImg.onload = function () {
fn(image, id);
self._loadingImages--;
if (self._loadingImages === 0) {
self.imagesLoaded();
}
}
};
This should work.
This Thread can help you: Check if an image is loaded (no errors) in JavaScript
I guess with jQuery you can achieve this such the answer on the link that I've copied below:
$("<img/>")
.load(function() { console.log("image loaded correctly"); })
.error(function() { console.log("error loading image"); })
.attr("src", $(originalImage).attr("src"))
;
Thanks to t.niese, this is my solution:
loadImage: function(image, id, fn) {
var bgImg = new Image(),
self = this;
// counting images currently loaded
this._loadingImages++;
// set error and onload callback and then image source
bgImg.onerror = function() {
throw new Error( "ERROR" );
};
bgImg.onload = function() {
fn(image, id);
self._loadingImages--;
if( self._loadingImages === 0 ) self.imagesLoaded();
}
bgImg.src = image;
},
After a user uploads a file we have to do some additional processing with the images such as resizing and upload to S3. This can take up to 10 extra seconds. Obviously we do this in a background. However, we want to show the user the result page immediately and simply show spinners in place until the images arrive in their permanent home on s3.
I'm looking for a way to detect that a certain image failed to load correctly (404) in a cross browser way. If that happens, we want to use JS to show a spinner in it's place and reload the image every few seconds until it can be successfully loaded from s3.
Handle the <img> element's onerror event.
First option:
<img src="picture1.gif" onerror="this.onerror=null;this.src='missing.gif';"/>
Second option:
<html>
<head>
<script type="text/javascript">
function ImgError(source){
source.src = "/noimage.gif";
source.onerror = "";
return true;
}
</script>
</head>
<body>
<img src="image_example1.jpg" onerror="ImgError(this)" />
</body>
</html>
PS: it's pure javascript! you don't need any libraries. (Vanilla JS)
Example in Fidler
https://jsfiddle.net/dorathoto/8z4Ltzp8/71/
From: http://lucassmith.name/2008/11/is-my-image-loaded.html
// First a couple helper functions
function $(id) {
return !id || id.nodeType === 1 ? id : document.getElementById(id);
}
function isType(o,t) { return (typeof o).indexOf(t.charAt(0).toLowerCase()) === 0;}
// Here's the meat and potatoes
function image(src,cfg) { var img, prop, target;
cfg = cfg || (isType(src,'o') ? src : {});
img = $(src);
if (img) {
src = cfg.src || img.src;
} else {
img = document.createElement('img');
src = src || cfg.src;
}
if (!src) {
return null;
}
prop = isType(img.naturalWidth,'u') ? 'width' : 'naturalWidth';
img.alt = cfg.alt || img.alt;
// Add the image and insert if requested (must be on DOM to load or
// pull from cache)
img.src = src;
target = $(cfg.target);
if (target) {
target.insertBefore(img, $(cfg.insertBefore) || null);
}
// Loaded?
if (img.complete) {
if (img[prop]) {
if (isType(cfg.success,'f')) {
cfg.success.call(img);
}
} else {
if (isType(cfg.failure,'f')) {
cfg.failure.call(img);
}
}
} else {
if (isType(cfg.success,'f')) {
img.onload = cfg.success;
}
if (isType(cfg.failure,'f')) {
img.onerror = cfg.failure;
}
}
return img;
}
And here how to use it:
image('imgId',{
success : function () { alert(this.width); },
failure : function () { alert('Damn your eyes!'); },
});
image('http://somedomain.com/image/typooed_url.jpg', {
success : function () {...},
failure : function () {...},
target : 'myContainerId',
insertBefore : 'someChildOfmyContainerId'
});
just bind the attr trigger on the error event.
$(myimgvar).bind('error',function(ev){
//error has been thrown
$(this).attr('src','/path/to/no-artwork-available.jpg');
}).attr('src',urlvar);
This worked for me (mine is in coffeescript). You'll need to replace with a spinner instead, of course.
checkImages = ->
$("img").each ->
$(this).error ->
$(this).attr("src", "../default/image.jpg")
$(document).on('page:load', checkImages)
I'm guessing the javascript equivalent is something like
function checkImages() {
$("img").each(function() {
$(this).error(function() {
$(this).attr("src", "../default/image.jpg");
});
});
};
$(document).on("page:load", checkImages);
I just did
if ($('#img')[0].naturalWidth > 0) {
as i noticed there was no naturalWidth if the image 404'd.
However, i can understand wanting to use a method above.