How to check image url is 404 using javascript - 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;
});

Related

Swapping an img src with a function (JavaScript)

I'm trying to swap two imgs in my webpage and can't wrap my head around why this code doesn't work. Any help would be appreciated.
This is in the HTML file:
<img onclick="swap(); "src="LaptopThin.jpg" id="LaptopPicture" />
while this is in a seperate javascript file:
function swap()
{
var picture = document.getElementById('LaptopPicture').src;
if (picture === 'LaptopThin.jpg') {
picture.src = 'ServerRack.jpg';
} else {
picture.src = 'LaptopThin.jpg';
}
I changed the code to:
function swap()
{
var picture = document.getElementById('LaptopPicture');
if (picture.src === 'LaptopThin.jpg') {
picture.src = 'ServerRack.jpg';
} else {
picture.src = 'LaptopThin.jpg';
}
}
and the picture is still not changing at all in the html file. The img stays on Laptopthin.jpg
You can't set the src property of picture because you set picture to the src property of an element already.
Change these lines:
var picture = document.getElementById('LaptopPicture').src;
if (picture === 'LaptopThin.jpg') {
to these:
var picture = document.getElementById('LaptopPicture');
if (picture.src === 'LaptopThin.jpg') {
It is because, the src property will give the absolute value of the image source not just the value set by the src attribute
function swap() {
var picture = document.getElementById('LaptopPicture');
if (picture.src.indexOf('LaptopThin.jpg') > -1) {
picture.src = 'ServerRack.jpg';
} else {
picture.src = 'LaptopThin.jpg';
}
}
Another option to try is to use getAttribute
function swap() {
var picture = document.getElementById('LaptopPicture');
if (picture.getAttribute('src')== 'LaptopThin.jpg') {
picture.src = 'ServerRack.jpg';
} else {
picture.src = 'LaptopThin.jpg';
}
}

JQuery - Check to see if an IMG src is valid

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;

Src for the images does not set properly

I have some divs that has a class named class='tweetCon'
each containing 1 image and I want to check if the image source exist or not so if it is available I dont do anything but if not I will change the image source with an appropriate image my code is as follow:
$('.tweetimgcon').children('img').each(function () {
imageExists($(this).attr("src"), function (exists) {
if (exists == true) {
} else {
$(this).attr("src", "https://pbs.twimg.com/profile_images/2284174758/v65oai7fxn47qv9nectx.png");
}
}, function () {
});
});
and also imageExists() is as follow:
function imageExists(url, callback,callback2) {
var img = new Image();
img.onload = function() { callback(true);callback2(); };
img.onerror = function() { callback(false);callback2(); };
img.src = url;
}
now the problem is that the src for the images that are not available does not set properly though when I check the src of those images by console.log it shows that they are properly set but it is not shown and when I use inspect element of chrome I can see that src is not set . Can anyone help me?
The point is $(this) doesn't point to your object, because you call $(this) inside your imgExists callback function but NOT the jQuery callback function each, so the this object doesn't point to your original img tag!
The solution should be save the object reference first, try the below:
$('.tweetimgcon').children('img').each(function () {
var _this = $(this);
imageExists($(this).attr("src"), function (exists) {
if (exists == true) {
} else {
_this.attr("src", "https://pbs.twimg.com/profile_images/2284174758/v65oai7fxn47qv9nectx.png");
}
}, function () {
});
});
Just for a little tip for a better callback function use call.
function imageExists(url, cb, ecb) {
var img = new Image();
img.onload = function() { cb.call(img,true,url); };
img.onerror = function() { ecb.call(img,false,url); };
img.src = url;
}
I added img as the first argument and that will then be your this keyword instead of window.
Testing Bin

JQuery: toggle conditions

I'm trying to add a toggle button to my website wherein it enables or disables the functionality of a certain feature, however while testing it, I bump into a problem wherein it does not alert even if the toggle works or the image changed. How can I make it work, any help and suggestion is appreciated.
HTML:
<img id="toggle-video" src="/images/Icons/10_device_access_video.png"
style="background-color:#C0C0C0; height: 20px; width:20px;" alt="" />
<img id="toggle-volume" src="/images/Icons/10_device_access_volume_on.png"
style="background-color:#C0C0C0; height: 20px; width:20px; margin-left:-5px;" alt="" />
JQUERY:
$("#toggle-video").on({'click':function() {
var origsrc = $(this).attr('src');
var src = '';
if (origsrc == '/images/Icons/10_device_access_video.png') src = '/images/Icons/10_device_stop_video.png';
// {
// alert(video success);
// }
if (origsrc == '/images/Icons/10_device_stop_video.png') src = '/images/Icons/10_device_access_video.png';
// {
// alert(volume success);
// }
$(this).attr('src', src);
}
});
You need to place the code which change the src value inside { } of your if condition:
$("#toggle-video").on({
'click': function () {
var origsrc = $(this).attr('src');
var src = '';
if (origsrc == '/images/Icons/10_device_access_video.png') {
src = '/images/Icons/10_device_stop_video.png';
alert('video success');
}
if (origsrc == '/images/Icons/10_device_stop_video.png') {
src = '/images/Icons/10_device_access_video.png';
alert('volume success');
}
$(this).attr('src', src);
}
});
Fiddle Demo
Code works fine.
You are trying to alert variables instead of string
alert(video success);
alert(volume success);
alert(`video success`);
alert(`volume success`);

JS if there is a slider show it

I'm no JS expert but I'm trying to alter this so that if there is a royalslider display it… if there isn't display the static image and the title and description. Any ideas as to why this isn't working? my head is currently spinning… I've left some space around the section I'm trying to add to the code under //royal slider fix and currently its just showing the title and description from the if statement. But, the markup is showing the slider div and outputting the code.
Any help would be very appreciated! You can preview this code and what I'm trying to do here... http://bvh.delineamultimedia.com/?page_id=2
;(function($) {
$.fn.SuperBox = function(options) {
var superbox = $('<div class="superbox-show"></div>');
var superboximg = $('<img src="" class="superbox-current-img">');
var superboxclose = $('<div class="superbox-close"></div>');
superbox.append(superboximg).append(superboxclose);
return this.each(function() {
$('.superbox').on('click', '.superbox-list', function() {
//allows for superbox to work inside of quicksand
$('ul.filterable-grid').css({overflow: 'visible'});
var currentimg = $(this).find('.superbox-img');
superbox.find('.title').remove();
superbox.find('.description').remove();
var imgData = currentimg.data();
superboximg.attr('src', imgData.img);
if (imgData.title) { superbox.append('<h3 class="title">'+imgData.title+'</h3>'); }
if (imgData.description) { superbox.append('<div class="description">' + imgData.description + '</div>'); }
//royal slider fix
superbox.find('.royalSlider').remove(); // remove the slider from previous events
var imgData = currentimg.data();
var sliderData = currentimg.next('.royalSlider'); // grab the slider html that we want to insert
superboximg.attr('src', imgData.img);
if (sliderData) { // show the slider if there is one
superbox.clone().append(sliderData); // clone the element so we don't loose it for the next time the user clicks
} else { // if there is no slider proceed as before
if (imgData.img) {
superbox.append(imgData.img);
}
if (imgData.title) {
superbox.append('<h3 class="title">' + imgData.title + '</h3>');
}
if (imgData.description) {
superbox.append('<div class="description">' + imgData.description + '</div>');
}
}
if($('.superbox-current-img').css('opacity') == 0) {
$('.superbox-current-img').animate({opacity: 1});
}
if ($(this).next().hasClass('superbox-show')) {
superbox.toggle();
} else {
superbox.insertAfter(this).css('display', 'block');
}
$('html, body').animate({
scrollTop:superbox.position().top - currentimg.width()
}, 'medium');
});
$('.superbox').on('hover', '.superbox-list', function(e) {
$(this).find('.overlay').stop()[(e.type == 'mouseenter') ? 'fadeIn' : 'fadeOut']('slow');
});
$('.superbox').on('click', '.superbox-close', function() {
$('.superbox-current-img').animate({opacity: 100}, 200, function() {
$('.superbox-show').slideUp();
});
});
});
};
})(jQuery);
This is only intended to be hints, not an attempt to solve the entire problem.
Try this:
var superbox = $('<div class="superbox-show"/>');
var superboximg = $('<img src="" class="superbox-current-img"/>');
var superboxclose = $('<div class="superbox-close"/>');
if (sliderData.length > 0)
Where is imgData.img getting its value?

Categories

Resources