JQuery - Check to see if an IMG src is valid - javascript

Is it possible to check to see if an img src is valid using jquery?
We have a dynamic site with hundreds of news articles - the majority of which contain images - basically theres a back-end bug and even if there isn't an image currently the image div is displayed - which is causing us a few issues.
<div class="imgBlock">
<img class="newsImg" src="db/imgart/10234.jpg" />
</div>
Is it possible to detect whether the img src is delivering an image via JQuery script?

function IsValidImageUrl(url) {
$("<img>", {
src: url,
error: function() { alert(url + ': ' + false); },
load: function() { alert(url + ': ' + true); }
});
}

Use the error handler like this:
$(".newsImg").error(function() {
alert("No image");
});
Or
var image = new Image();
image.src = "db/imgart/10234.jpg";
if (image.width == 0) {
alert("No image");
}

Use simple css:
<style type="text/css">
.hidden {
display: none;
{
.visible {
display: block;
}
</style>
then script
var imgDiv = document.getElementById('img1'); //your div id
var imgsrc = "db/imgart/10234.jpg"; //or document.getElementById(img1).getElementsByTagName('img');
var img = new Image();
img.onerror = function (evt){
alert(this.src + " can't be loaded.");
//hide <div>
imgDiv.setAttribute('class', 'hidden');
}
img.onload = function (evt){
alert(this.src + " is loaded.");
//show div
imgDiv.setAttribute('class', 'visible');
}
img.src = imgsrc;

Related

Detect dynamically appended images load event pure javascript [duplicate]

Say, user opens a page, clicks on a button, and popup with images appears. How do I detect when all of the images have been loaded? I can't use window.onload here, since the page had already been loaded with all the assets. To make it clear, I want to find out final extents of the popup.
Popup is added to DOM like so:
var popup = document.createElement('div');
popup.innerHTML = '...';
document.body.appendChild(popup);
Simply:
var image = document.getElementById('image');
image.onload = function () {
alert ("The image has loaded!");
};
setTimeout(function(){
image.src = "http://lorempixel.com/500/500";
}, 5000);
<img id="image" src="">
See https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload and Javascript callback for knowing when an image is loaded for more.
Based on this answer. Hopefully that is enough.
var cons = document.querySelector('#console');
var popup = document.createElement('div');
popup.className = 'popup';
popup.innerHTML = _.range(10).map(function(i) {
return '<img src="http://via.placeholder.com/50/50">';
}).join('');
document.body.insertBefore(popup, cons);
waitForImages(popup).then(function() {
d('loaded');
})
function d(s) {
var text = document.createTextNode(s);
cons.appendChild(text);
var br = document.createElement('br');
cons.appendChild(br);
}
function waitForImages(el) {
var images = document.querySelectorAll('img');
return Promise.all(_.compact(_.map(images, function(img) {
if (img.complete) {
d('img.complete');
return;
} else
return new Promise(function(resolve, reject) {
img.addEventListener('load', function() {
d('onload event');
resolve();
});
});
})));
}
.popup {
overflow: hidden;
}
img {
float: left;
margin: 0 5px 5px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.5.0/bluebird.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<div id="console">
</div>

Detect when images added to DOM have been loaded

Say, user opens a page, clicks on a button, and popup with images appears. How do I detect when all of the images have been loaded? I can't use window.onload here, since the page had already been loaded with all the assets. To make it clear, I want to find out final extents of the popup.
Popup is added to DOM like so:
var popup = document.createElement('div');
popup.innerHTML = '...';
document.body.appendChild(popup);
Simply:
var image = document.getElementById('image');
image.onload = function () {
alert ("The image has loaded!");
};
setTimeout(function(){
image.src = "http://lorempixel.com/500/500";
}, 5000);
<img id="image" src="">
See https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload and Javascript callback for knowing when an image is loaded for more.
Based on this answer. Hopefully that is enough.
var cons = document.querySelector('#console');
var popup = document.createElement('div');
popup.className = 'popup';
popup.innerHTML = _.range(10).map(function(i) {
return '<img src="http://via.placeholder.com/50/50">';
}).join('');
document.body.insertBefore(popup, cons);
waitForImages(popup).then(function() {
d('loaded');
})
function d(s) {
var text = document.createTextNode(s);
cons.appendChild(text);
var br = document.createElement('br');
cons.appendChild(br);
}
function waitForImages(el) {
var images = document.querySelectorAll('img');
return Promise.all(_.compact(_.map(images, function(img) {
if (img.complete) {
d('img.complete');
return;
} else
return new Promise(function(resolve, reject) {
img.addEventListener('load', function() {
d('onload event');
resolve();
});
});
})));
}
.popup {
overflow: hidden;
}
img {
float: left;
margin: 0 5px 5px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.5.0/bluebird.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<div id="console">
</div>

How to check image url is 404 using javascript

Use Case:
when src is not null and alt tag is not null then show image of src.
then check src image url is not 404.
when src is null and alt is not null the show image of first name.
when src and alt are null then show default image
HTML:
<img class="imagelazy" id="lazyimage" src="http://url" alt="ankit">
Javascript:
function imagelazy() {
$(document).ready(function()
{
var image = $(".imagelazy").attr('src');
var altdata = $(".imagelazy").attr('alt');
var alt = $(".imagelazy").attr('alt').split("");
//var imagepath="http://im.gifbt.com/userimages/"+alt[0].toLowerCase()+".jpg";
var defaultimage = "http://im.gifbt.com/img/no-pic.jpg";
console.log(image);
console.log(alt);
$(".imagelazy img")
.error(function() {
$(this).hide();
})
.attr("src", defaultimage);
if (image != '' && altdata != '') {
console.log("afeef");
$('.imagelazy').bind('error', function() {
$(this).attr("src", defaultimage);
});
$(".imagelazy img")
.error(function() {
$(this).hide();
})
.attr("src", defaultimage);
} else if (image == '' && altdata != '') {
$.each($('.imagelazy'), function(index, value) {
var alt1 = $(this).attr('alt').split("");
console.log(alt1);
if (alt1 != '') {
var imagepath1 = "http://im.gifbt.com/userimages/" + alt1[0].toLowerCase() + ".jpg";
}
console.log(this.outerHTML);
console.log(imagepath1);
$(this).attr("src", imagepath1);
});
} else if (altdata == '' && image == '') {
$.each($('.imagelazy'), function(index, value) {
$(this).attr("src", defaultimage);
console.log(this.outerHTML);
});
}
});
}
Problem
Script is not working when scrolling down the page.
When the image is set in src and alt tag is set then also first name image is displayed.
onerror is not working in js.
i have googled a lot coudln"t found the solution for this issue.
i have found lazy.min.js js which set src="" and data-src="pathimage"
would handled this issue.
our requirement is optimize html that why im searching for alternate solution through js.
i have found jquery link : https://api.jquery.com/error/
jQuery Ajax:
$.ajax({
url:'http://www.example.com/somefile.ext',
type:'HEAD',
error: function()
{
//file not exists
},
success: function()
{
//file exists
}
});
Javascript:
function UrlExists(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
Image check:
function ImageExist(url)
{
var img = new Image();
img.src = url;
return img.height != 0;
}
Other:
$.get(url)
.done(function() {
// exists code
}).fail(function() {
// not exists code
})
HTML:
<img src="image.gif" onerror="imgError()" />
function imgError()
{
alert('The image could not be loaded.');
}
Use onerror event of HTML img tag for 2,3 and 4th scenerio. http://www.w3schools.com/jsref/event_onerror.asp
<img src="invalid_link" onerror="this.onerror=null;this.src='https://www.google.com/images/srpr/logo11w.png';" alt="">
isn't this selector is wrong:
$(".imagelazy img")
This should be either:
$("img.imagelazy")
or just image class name:
$(".imagelazy")
And also you don't have to wrap the doc ready block in any function block. and you can optimize your code like:
$('.imagelazy').attr('src', function() {
var alt1 = $(this).attr('alt').split("");
if (alt1 != '') {
var imagepath1 = "http://im.gifbt.com/userimages/" + alt1[0].toLowerCase() + ".jpg";
}
return imagepath1;
});

jQuery switch image with fade

I have a script which changes some images on hover. Works really well, however I would like to add a little fade between the two images. Here is the script. Really new to jQuery so I'm a little confused where to add it. Any help would be appreciated
jQuery(document).ready(function ($) {
var img_src = "";
var new_src = "";
$(".rollover").hover(function () {
img_src = $(this).attr('src');
new_src = $(this).attr('rel');
$(this).attr('src', new_src);
$(this).attr('rel', img_src);
}, function () {
$(this).attr('src', img_src);
$(this).attr('rel', new_src);
});
//preload images
var cache = new Array();
//cycle through all rollover elements and add rollover img src to cache array
$(".rollover").each(function () {
var cacheImage = document.createElement('img');
cacheImage.src = $(this).attr('rel');
cache.push(cacheImage);
});
function imageSwitch(img) {
var src = img.attr('src');
var rel = img.attr('rel');
img.fadeOut('fast', function() {
img.attr('src', rel);
img.attr('rel', src);
img.fadeIn('fast');
});
}
$(".rollover").on('mouseenter', function() {
imageSwitch($(this));
});
a small search give me that : http://www.simonbattersby.com/demos/crossfade_demo_basic.htm i think it's kinda what you're looking for.
or else you with thread that do something also :
jQuery Change Image src with Fade Effect
it would be better to use .mouseenter for this.
and you could do .animate() opacity to 0 and in the call back you would change the image src, so that the src change after the animation ended.
$('.rollover').mouseenter(function () {
var me = $(this),
new_src = me.attr('rel'),
anmiation_duration = 300; // 300ms
me.animate({
opacity: 0
}, anmiation_duration, function () {
me.attr('src', new_src).css({'opacity':'1'});
})
});
After the src is changed you can do another .animate() to set the opacity back to 1.
I would however suggest to have the other image already displayed behind the first image, (images placed over each other using position:absolut). That way the opacity change would create sort of morf effect.
Briefly tested, thanks to #Oksid for the mouseenter comment.
EDITED
The HTML:
<img class="front rollover" src="http://placehold.it/350x150/006699" rel="http://placehold.it/350x150/000000" />
The CSS:
.image_holder {
position: relative;
}
.image_holder img {
position: absolute;
top: 0;
left: 0;
z-index: 1;
}
.image_holder img.front {
z-index: 2 !important;
}
The jQuery:
function init_rollovers() {
$(".rollover").each(function() {
var w = $(this).width()+'px';
var h = $(this).height()+'px';
var src = $(this).attr('src');
var rel = $(this).attr('rel');
$(this).addClass('shown');
if (!$(this).parents('.image_holder').length) {
$(this).wrap('<div class="image_holder" style="width:'+w+';height:'+h+';"></div>');
$(this).parents('.image_holder').append('<img src="'+rel+'" />');
}
});
}
init_rollovers();
function doImageSwitch(el, speed=425) {
var front = el.find(".front");
if (front.hasClass('shown')) {
front.fadeTo(speed, 0, function() {
$(this).removeClass('shown');
});
}
else {
front.animate({
opacity: 1
}, speed, function() {
$(this).addClass('shown');
});
}
}
$(document).on('mouseenter', '.image_holder', function() {
doImageSwitch($(this));
});

Opening an image in a popup: how to get its size when the image is loaded?

I am writing a script that looks for links of the kind <a href='image_url'>...</a>, where image_url is the url of an image, and then adds to those tags an onclick='popupImage(this)' attribute to them that opens a popup displaying the image. I know how to look for those tags, and my question is about writing the popupImage function. So far, I have
function popupImage(link){
window.open(link,'image','width=400,height=400');
}
This works pretty well, but I would like to resize the popup to fit the image, once it's loaded. Thus, I would probably need something of the kind
function popupImage(link){
w=window.open(link,'image','width=400,height=400');
w.onload = function(){
... Do something to get the size of the image...
... Resize the popup (this, I know how to do)...
}
}
But I don't know how to access the image loaded by the window, since it has no DOM... The thing is that I really don't want to write some HTML into the popup to display the image (for some other reasons).
Any suggestion would be much appreciated. Thanks in advance!
Here is a solution based on your updated question
HTML
One
Two
Three
Javascript
(function () {
window.addEventListener("load", function onLoad() {
this.removeEventListener("load", onLoad);
Array.prototype.forEach.call(document.getElementsByTagName("a"), function (anchor) {
anchor.addEventListener("click", function (evt) {
evt.preventDefault();
var newImg = document.createElement("img");
newImg.src = anchor.href;
newImg.addEventListener("load", function imgLoad() {
this.removeEventListener("load", imgLoad);
window.open(newImg.src, "image", "width=" + newImg.width + "px,height=" + newImg.height + "px");
}, false);
}, false);
});
}, false);
}());
On jsfiddle
No longer a solution after question update.
Here is a possible solution
CSS
.image {
width: 50px;
height: auto;
}
HTML
<img class="image" src="http://img145.imageshack.us/img145/1750/barcelonaagbartowernighnx7.jpg" />
<img class="image" src="http://img515.imageshack.us/img515/5390/005cc0.jpg" />
<img class="image" src="http://imageshack.us/a/img708/9470/compatiblechrome.gif" />
Javascript
(function (global) {
global.addEventListener("load", function onLoad() {
global.removeEventListener("load", onLoad);
Array.prototype.forEach.call(document.getElementsByTagName("img"), function (image) {
var newImg = document.createElement("img");
newImg.src = image.src;
image.addEventListener("click", function () {
global.open(image.src, "image", "width=" + newImg.width + "px,height=" + newImg.height + "px");
}, false);
});
}, false);
}(window));
On jsfiddle

Categories

Resources