Javascript jQuery How to load default image if - javascript

I wanted to load the default image if the user's one didn't exist. I tried this but it didn't work.
$('#avatar').load(function(){
// ... loaded
}).error(function(){
// ... not loaded
$(this).attr('src','/images2/no-avatar2.png');
});
Anyone know how I could do this?
Someone uses this:
function loadDefault(f, ff) {
img = document.getElementById(f);
if(!img.complete) {
img.src = ff;
}
if(typeof(img.naturalWidth) != "undefined" && img.naturalWidth == 0) {
img.src = ff;
}
}
function init() {
setTimeout("loadDefault('side_avatar', '/images/default/avatar_player_profile.gif')", 100);
setTimeout("imageResize(740)", 100);
tooltip = new ToolTip();
tooltip.init('hoverBox', 'loading...');
}
How could I use something like this?

It looks like you are missing your load url as the first parameter of the load() function. Also, without seeing your HTML, I'll assume #avatar is an img tag the way you are using it in the error function. I don't think you can load HTML into an img so you may be better off structuring your html and js like so:
HTML Example:
<div id="avatarDiv">
<img id="avatar" src="" alt="" />
</div>
JS Example:
$('#avatarDiv').load('avatar.php', function() {
// ... loaded
}).error(function() {
// ... not loaded
$('img#avatar').attr('src','/images2/no-avatar2.png');
});
Then just make sure your avatar.php file returns the full html of the image object:
<img id="avatar" src="successful-avatar.jpg" alt="" />
Docs: http://api.jquery.com/load/

I'd try something like this:
$.get("get-avatar.php", function(response) {
$("#avatar").attr('src', response);
}).error(function(response) {
$(this).attr('src', '/images2/no-avatar2.png');
})
as long as avatar.php returns a http error message if the image doesn't exist.

This routine uses ajax to see if the image file exists:
HTML:
<img id='avatar' src='/images2/avatar2find.png' alt='No Image Available'></img>
Script:
$(window).load(function() {
var $img = $('#avatar');
$.ajax({
url: $img.attr('src'),
type: 'get',
statusCode: {
404: function() {
$img.attr('src', '/images2/no-avatar2.png');
}
},
error:
function() {
// do something?
}
});
});

Related

How can I apply a watermark in images using JavaScript?

I'm using angularJS and need to apply a watermark programatelly in images by calling an JS function. What I have is:
<figure><img class="watermark" ng-src="{{applyWatermark(img.url)}}"></figure>
So, I need to call that function applyWatermark (not implemented yet) and return a img with the watermark, but I'm not sure how can I build this function. Should it return the image? Can someone provide me some example how can I do this?
EDIT:
I did this, but it's not working:
$(function applyWatermark(image) {
watermark([image, 'watermark.png'])
.image(watermark.image.lowerRight())
.then(function (img) {
return img
});
})
Any idea?
Using watermark.js:
watermark(['/img/forest.jpg', '/img/logo.png'])
.image(watermark.image.lowerRight(0.5)) // Or lowerRight() for no opacity
.then(function (img) {
document.getElementById('alpha-image').appendChild(img);
});
If this doesn't work for you, maybe try this:
$.ajax({
url: 'http://www.example.com/your-image.jpg',
type: 'HEAD',
error: function() {
// File isn't found
},
success: function() {
// File is found! Do the watermarkage.
}
});
to test if the image exists before processing.

How to run code after an image has been loaded using JQuery

I'm trying to load an element only after the img element has been loaded, but I've tried everything I can think of and nothing is working. Right now I'm trying to see where the code stops working and I found that the alert I set up isn't running after the line I need the code to execute from.
$img = $('#picture');
function bubbleOnLoad() {
$(document).ready(function() {
$img.load(function(){
alert('document loaded')
$('#left-bubble').show();
})
})
The $img is defined within a function. The alert works at the document.ready line but not after the $img.load. I have tried to add eventlisteners, jquery .on, .load, and a bunch of others. I'm also calling the function to run within my init function. Can someone explain to me why nothing is working?
function choosePic()
$('.speechbubble').hide();
$('#picture').remove();
var randomNum = Math.floor(Math.random() * samplePics.length);
var img = new Image();
img.onload = function() {
$('.playing-field').prepend(img);
handleImageLoad();
}
img.src = samplePics[randomNum];
img.id = "picture";
}
var samplePics =
"assets/images/barack-obama.jpg",
"assets/images/donald-trump_3.jpg",
"assets/images/dt-2.jpg",
"assets/images/bill-clinton.jpg",
"assets/images/Rose-Byrne.jpg",
"assets/images/pic.jpeg",
"assets/images/priest.jpg",
"assets/images/tb.jpg",
"assets/images/test.jpg",
"assets/images/amy-poehler.jpg",
"assets/images/stephen-colbert.jpg",
"assets/images/aziz-ansari.jpg"
];
You had some syntax errors in your code which I corrected and came up with this:
function bubbleOnLoad() {
$img = $('#picture');
$img.load(function () {
alert('document loaded');
$('#left-bubble').show();
});
}
$(document).ready(function () {
bubbleOnLoad();
});
Here is the JSFiddle demo
In you code you are not even telling the browser it's supposed to run a code after image load. you should do something like this:
$(function(){
// DOM Content is ready, let's interact with it.
$('#picture').attr('src', 'image.jpg').load(function() {
// run code
alert('Image Loaded');
});
});
Also according to docs a common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:
It doesn't work consistently nor reliably cross-browser
It doesn't fire correctly in WebKit if the image src is set to the same src as before
It doesn't correctly bubble up the DOM tree
Can cease to fire for images that already live in the browser's cache
Try this jQuery plugin waitForImages
https://github.com/alexanderdickson/waitForImages
//Javascript/jQuery
$(document).ready(function(){
var counter = 0,totalImages= $('#preloader').find('img').length;
$('#preloader').find('img').waitForImages(function() {
//fires for all images waiting for the last one.
if (++counter == totalImages) {
$('#preloader').hide();
yourCallBack();
}
});
});
/*css*/
#preloader{
position:absolute;
top:-100px;/*dont put in DOM*/
}
#preloader > img{
width:1px;
height:1px;
}
<!--HTML [add the plugin after jQuery] -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.waitforimages/1.5.0/jquery.waitforimages.min.js" ></script>
<!--HTML [after body start] -->
<div id=preloader>
<img src="1.jpg" />
<img src="2.jpg" />
<img src="3.png" />
<img src="4.gif" />
<img src="5.jpg" />
</div>
You can only access the HTML element after it was created in DOM.
Also you need to check if the image was loaded before showing.
Thus your code need to look something as below:
$(document).ready(function() {
bubbleOnLoad();
});
function bubbleOnLoad() {
var newSrc = "https://lh5.googleusercontent.com/-lFNPp0DRjgY/AAAAAAAAAAI/AAAAAAAAAD8/Fi3WUhXGOY0/photo.jpg?sz=328";
$img = $('#picture');
$img.attr('src', newSrc) //Set the source so it begins fetching
.each(function() {
if(this.complete) {
alert('image loaded')
$('#left-bubble').show();
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="left-bubble" style="display:none">
<img id="picture"/>
</div>

jQuery: Execute function as soon as a subset of images have loaded

I have a slideshow that I need to initialize with jQuery. The initialization requires all slideshow images to be fully loaded, so that I can get their actual width and height. I can not change this part.
Consider the following layout:
<div class="slideshow">
<img />
<img />
<img />
</div>
<img />
<img />
<img />
I need to initialize the slideshow as soon as the three images inside the slideshow container have been loaded. I can NOT wait until the rest of the images on the page have been loaded, as there might be thousands of images.
Any ideas how I could solve this?
As per my comment, you can wrap the checking/load behavior in a jQuery plugin and return a single promise like this:
$.fn.imagesLoaded = function () {
var def = $.Deferred();
var count = this.length;
this.each(function () {
if (this.complete) {
if (!--count) {
def.resolve();
}
} else {
$(this).load(function () {
if (!--count) {
def.resolve();
}
});
}
});
return def.promise();
}
and then simply use like this:
$('.slideshow img').imagesLoaded().done(function () {
alert("loaded");
});
Here's what I ended up using, quite a bit more complicated than I'd hoped:
// Prepare the slideshow as soon as all of its images have been loaded
var slideshowImages = $('.slideshow img');
var slideshowImagesLoadedCount = 0;
// Check how many images have already been loaded
slideshowImages.each(function() {
if(this.complete) {
slideshowImagesLoadedCount++;
}
});
// If all the images have loaded already, prepare the slideshow
if(slideshowImagesLoadedCount === slideshowImages.length) {
prepareSlideshow();
} elseĀ {
// Otherwise wait until all images have been loaded
slideshowImages.load(function() {
slideshowImagesLoadedCount++;
if(slideshowImagesLoadedCount === slideshowImages.length) {
prepareSlideshow();
}
});
}

How to change path of img for dynamically loaded template

Have a template with button..
Onclick of the button loading another template using Jquery load().
Example:
Template1:
<div id='tp1'>
<button>Load</button>
<div class="sub"></div>
</div>
Template2:
<div id='tp2'>
<img src='../abc/amd/aa.jpg' class="iPath"/>
<img src='../edf/dfv/bb.jpg' class="iPath"/>
<img src='../fgh/vbf/cc.jpg' class="iPath"/>
</div>
Now I need to change the src of tp2 for all the images, but the paths for each image is different.
img1 path: ../qwe/afg/aa.jpg
img2 path: ../asd/zvb/bb.jpg
img3 path: ../zxc/qrt/cc.jpg
Jquery:
$(document).ready(function(){
$('button').click(function(){
$('.sub').load("../abbb.html");
console.log($('.iPath'));
});
});
But here the iPath is undefined, because the load of the template 2 is not rendered.
How do I know whether the page is successfully loaded or not, so that it will be easy to change the source of the page....
Try adding a callback to load(), with required data.
A callback function that is executed when the request completes.
$('.sub').load("../abbb.html",function(data){
$(data).find('.iPath');
});
To change the src of image, you need to set the attribute using
$('.sub').load("../abbb.html",function(data){
$(data).find('.iPath').each(function(){
$(this).attr('src','...')
});
});
Try Like
$('img').each(function () {
var src = $(this).attr('src');
$(this).attr('src', 'newsrc');
});
OR
$("#ID > img").each(function() {
var src = $(this).attr('src');
$(this).attr('src', 'newsrc');
});
Load Using
$(function()
{
$("#div").load("page.html", function(responseText, statusText, xhr)
{
if(statusText == "success")
alert("Successfully loaded the content!");
if(statusText == "error")
alert("An error occurred: " + xhr.status + " - " + xhr.statusText);
});
});

Check connection for url - image load

I make some script where i load many images from other sites. When it finish load i do:
$container.imagesLoaded( function(){
alert('OK');
.... /// do masonry layout
});
But i have problem when some img url is not available - script whole time try to load images from url with which he cant connect and function from imagesLoaded isnt executed. How can i resolve this problem and remove img that doesnt want to load from loading, after for example 10 seconds.
<p>
<span onclick="checkurlExist()">Click me!</span>
</p>
<script type="text/javascript">
function checkurlExist() {
$.ajax({
url:"http://yoururl.com/image.png",
statusCode: {
404: function () {
alert("URL not found");
}
},
success: function () {
alert('success');
},
error: function () {
alert('error');
}
});
}
</script>

Categories