How to reload tile which is not loaded in leaflet.js - javascript

I am searching for solution, how to reload tile in leaflet.js which is not loaded due error 503.
Thank you

Looking at the API I put this code together which should help you solve the problem:
function reloadImg() { // reload image by changing its src
var src = $(this).attr("src");
var i = src.lastIndexOf('?');
if(i > 0) { // remove previous cache string
src = src.substring(0, i);
}
$(this).attr("src", src + "?nocache=" + (Math.random() * 1000));
}
map.on('layeradd', function(ILayer) { // on adding a new tile
if($.isFunction(ILayer.layer.getContainer)) { // get the container holding the images
$("img", ILayer.layer.getContainer()).error(reloadImg); // apply error handling event
}
});

Related

Image src relative path to absolute path

I have website and now making a hybrid app for it.
I get all my blog post using Jquery get method.
However the issue is that <img src="/media/image.png"> is sometime relative url and sometime an absolute url.
Everytime an absolute url breaks the image showing 404 error.
How to write Jquery function to find if src is absolute and change it to
https://www.example.com/media/image.png
I will not be able to provide any code samples I have tried since I am not a front end developer and tried whole day solving it.
Note: I need to change images present only in <div id="details"> div.
You should always use same path for all the images, but as of your case you can loop through images and append the domain, as of the use case I have added the domain in variable you can change it as per your requirement.
You can use common function or image onload to rerender but I h
Note: image will rerender once its loaded.
var imageDomain = "https://homepages.cae.wisc.edu/~ece533/";
//javascript solution
// window.onload = function() {
// var images = document.getElementsByTagName('img');
// for (var i = 0; i < images.length; i++) {
// if (images[i].getAttribute('src').indexOf(imageDomain) === -1) {
// images[i].src = imageDomain + images[i].getAttribute('src');
// }
// }
// }
//jquery solution
var b = 'https://www.example.com';
$('img[src^="/media/"]').each(function(e) {
var c = b + $(this).attr('src');
$(this).attr('src', c);
});
//best approach you are using get request
//assuming you are getting this respone from api
var bArray = ["https://www.example.com/media/image.png", "/media/image.png"]
var imgaesCorrected = bArray.map(a => {
if (a.indexOf(b) === -1) {
a = b+a;
}
return a;
});
console.log(imgaesCorrected);
img {
width: 50px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="/media/image.png">
<img src="https://www.example.com/media/image.png">
document.querySelectorAll('#details img').forEach(img => {
const src = img.getAttribute('src');
// use regex, indexOf, includes or whatever to determine you want to replace the src
if (true) {
img.setAttribute('src', 'https://www.example.com' + src);
}
});
The best would be to do this with the response html from the ajax request before inserting into the main document so as to prevent needless 404 requests made while changing the src
Without seeing how you are making your requests or what you do with the response here's a basic example using $.get()
$.get(url, function(data){
var $data = $(data);
$data.find('img[src^="/media/"]').attr('src', function(_,existing){
return 'https://www.example.com' + existing
});
$('#someContainer').append($data)'
})
You can just get all the images from an object and find/change them if they don't have absolute url.
var images = $('img');
for (var i = 0 ; i < images.length ; i++)
{
var imgSrc = images[i].attributes[0].nodeValue;
if (!imgSrc.match('^http'))
{
imgSrc = images[i].currentSrc;
console.info(imgSrc);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="/media/test.jpg">
<img src="/media/test.jpg">
<img src="https://www.example.com/media/test.jpg">

Change class on multiple img in array

This is my first post here, I always found solutions on this page, so thank you for that.
I have a problem with .removeClass and .addClass in my last program.
I load multiple pictures into array Frames and I want change all (previous-image) to (current-image) in frames[0]. Here is my code, it is change class only on second image. Here is code:
function loadImage() {
// Creates a new <li>
var li = document.createElement("li");
// Generates the image file name using the incremented "loadedImages" variable
var imageName = "graphics/img/Dodge_Viper_SRT10_2010_360_720_50-" + (loadedImages + 1) + ".jpg";
var imageName1 = "graphics/img/Dodge_Viper_SRT10_2010_360_720_50-" + (loadedImages + 1) + ".jpg";
/*
Creates a new <img> and sets its src attribute to point to the file name we generated.
It also hides the image by applying the "previous-image" CSS class to it.
The image then is added to the <li>.
*/
var image = $('<img>').attr('src', imageName).addClass("previous-image").appendTo(li) && $('<img>').attr('src', imageName1).addClass("previous-image light-image").appendTo(li);
// We add the newly added image object (returned by jQuery) to the "frames" array.
frames.push(image);
// We add the <li> to the <ol>
$images.append(li);
/*
Adds the "load" event handler to the new image.
When the event triggers it calls the "imageLoaded" function.
*/
$(image).load(function() {
imageLoaded();
});
};
function imageLoaded() {
// Increments the value of the "loadedImages" variable
loadedImages++;
// Updates the preloader percentage text
$("#spinner span").text(Math.floor(loadedImages / totalFrames * 100) + "%");
// Checks if the currently loaded image is the last one in the sequence...
if (loadedImages == totalFrames) {
// ...if so, it makes the first image in the sequence to be visible by removing the "previous-image" class and applying the "current-image" on it
frames[0].removeClass("previous-image").addClass("current-image");
/*
Displays the image slider by using the jQuery "fadeOut" animation and its complete event handler.
When the preloader is completely faded, it stops the preloader rendering and calls the "showThreesixty" function to display the images.
*/
$("#spinner").fadeOut("slow", function() {
spinner.hide();
showThreesixty();
});
} else {
// ...if not, Loads the next image in the sequence
loadImage();
}
};
This is, how it looks in browser:
<ol><li><img src="graphics/img/Dodge_Viper_SRT10_2010_360_720_50-1.jpg" class="previous-image"><img src="graphics/img/Dodge_Viper_SRT10_2010_360_720_50-1.jpg" class="light-image current-image"></li></ol>
This is, what I want:
<ol><li><img src="graphics/img/Dodge_Viper_SRT10_2010_360_720_50-1.jpg" class="current-image"><img src="graphics/img/Dodge_Viper_SRT10_2010_360_720_50-1.jpg" class="light-image current-image"></li></ol>
When I change this
var image = $('<img>').attr('src', imageName).addClass("previous-image").appendTo(li) && $('<img>').attr('src', imageName1).addClass("previous-image light-image").appendTo(li);
to this
var image = $('<img>').attr('src', imageName1).addClass("previous-image light-image").appendTo(li) && $('<img>').attr('src', imageName).addClass("previous-image").appendTo(li);
it still change only second img. Any help?
var image = $('<img>').attr('src', imageName).addClass("previous-image").appendTo(li) && $('<img>').attr('src', imageName1).addClass("previous-image light-image").appendTo(li);
is not doing what you think it is. It's only using the second element you declare. They both get appended to the page (because the appendTo method runs), but && is a logical operator, it's not used for concatenation, so the variable "image" only contains the second image you declared.
This will work instead:
var image = $('<img>', { "src": imageName, "class": "previous-image" });
image = image.add($('<img>', { "src": imageName1, "class": "previous-image light-image" }));
image.appendTo(li);
If you are just trying to replace all the previous-image classes with current image then you can do this:
$('img.previous-image').each(function(){
$(this).addClass("current-image").removeClass("previous-image");
});

Why does this "loading message" script not work in FF?(javascript)

I have this script which should show the text "Loading..." while images are loading, then change the text to "loaded" when all images are loaded. I added a button to load new images to make sure that it works for dynamically loaded images as well.
This works perfectly in Chrome but in Firefox the "Loading..." text never appears. I have no idea why this would be. The page begins loading and not all images are loaded so it should create the text "Loading.." but it doesn't. Then when all images are done loading the text "Loading" appears.
I just don't get why one message would appear and the other wouldn't. Especially because there are no qualifications that have to be met before creating the "Loading..." text, it should just fire automatically.
jsfiddle Example | Full Page Example
$(document).ready(function() {
var checkComplete = function() {
if($('img').filter(function() {return $('img').prop('complete');}).length == $('img').length) {
$('.status').text('Loaded');
} else {
$('.status').text('Loading...');
}
};
$('img').on('load',function() {
checkComplete();
});
$('#button').click(function() {
$('img.a').attr('src' , 'http://farm9.staticflickr.com/8545/8675107979_ee12611e6e_o.jpg');
$('img.b').attr( 'src' , 'http://farm9.staticflickr.com/8382/8677371836_651f586c99_o.jpg');
checkComplete();
});
checkComplete();
});
You have several issues in the code.
First off, the checkComplete() function is not written correctly. It should be this:
var checkComplete = function() {
var imgs = $('img');
if(imgs.filter(function() {return this.complete;}).length == imgs.length) {
$('.status').text('Loaded');
} else {
$('.status').text('Loading...');
}
};
The main fix here is that the filter callback needs to refer to this.complete, not to $('img').prop('complete') because you are trying to filter a single item at a time.
Second off, you are relying on both .complete and .load working correctly AFTER you've changed the .src value. This is explicitly one of the cases where they do not work properly in all browsers.
The bulletproof way to work around this is to create a new image object for the new images, set the onload handler before you set the .src value and when both onload handlers have fired, you will know that both new images are loaded and you can replace the once you have in the DOM with the new ones.
Here is a version that works in FF:
$(document).ready(function() {
$('#button').click(function() {
var imgA = new Image();
var imgB = new Image();
imgA.className = "a";
imgB.className = "b";
var loaded = 0;
imgA.onload = imgB.onload = function() {
++loaded;
if (loaded == 2) {
$("img.a").replaceWith(imgA);
$("img.b").replaceWith(imgB);
$('.status').text('Loaded');
}
}
// the part with adding now to the end of the URL here is just for testing purposes to break the cache
// remove that part for deployment
var now = new Date().getTime();
imgA.src = 'http://farm9.staticflickr.com/8545/8675107979_ee12611e6e_o.jpg?' + now;
imgB.src = 'http://farm9.staticflickr.com/8382/8677371836_651f586c99_o.jpg?' + now;
$('.status').text('Loading...');
});
});
Working demo: http://jsfiddle.net/jfriend00/yy7GX/
If you want to preserve the original objects, you can use the newly created objects only for preloading the new images and then change .src after they've been preloaded like this:
$(document).ready(function() {
$('#button').click(function() {
var imgA = new Image();
var imgB = new Image();
var loaded = 0;
imgA.onload = imgB.onload = function() {
++loaded;
if (loaded == 2) {
$("img.a")[0].src = imgA.src;
$("img.b")[0].src = imgB.src;
$('.status').text('Loaded');
}
}
// the part with adding now to the end of the URL here is just for testing purposes to break the cache
// remove that part for deployment
var now = new Date().getTime();
imgA.src = 'http://farm9.staticflickr.com/8545/8675107979_ee12611e6e_o.jpg?' + now;
imgB.src = 'http://farm9.staticflickr.com/8382/8677371836_651f586c99_o.jpg?' + now;
$('.status').text('Loading...');
});
});
Working demo of this version: http://jsfiddle.net/jfriend00/ChSQ5/
From the jQuery API .load method
Caveats of the load event when used with images
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

javascript preloader/progress/percentage

I'm having trouble finding any good information on how to make a javascript(or jquery) progress bar WITH text that tells you the percentage.
I don't want a plug in, I just want to know how it works so that I can adapt it to what I need. How do you preload images and get a variable for the number of images that are preloaded. Also, how do you change html/css and-or call a function, based on the number of images that are loaded already?
<img> elements have an onload event that fires once the image has fully loaded. Therefore, in js you can keep track of the number of images that have loaded vs the number remaining using this event.
Images also have corresponding onerror and onabort events that fire when the image fails to load or the download have been aborted (by the user pressing the 'x' button). You also need to keep track of them along with the onload event to keep track of image loading properly.
Additional answer:
A simple example in pure js:
var img_to_load = [ '/img/1.jpg', '/img/2.jpg' ];
var loaded_images = 0;
for (var i=0; i<img_to_load.length; i++) {
var img = document.createElement('img');
img.src = img_to_load[i];
img.style.display = 'hidden'; // don't display preloaded images
img.onload = function () {
loaded_images ++;
if (loaded_images == img_to_load.length) {
alert('done loading images');
}
else {
alert((100*loaded_images/img_to_load.length) + '% loaded');
}
}
document.body.appendChild(img);
}
The example above doesn't handle onerror or onabort for clarity but real world code should take care of them as well.
What about using something below:
$('#btnUpload').click(function() {
var bar = document.getElementById('progBar'),
fallback = document.getElementById('downloadProgress'),
loaded = 0;
var load = function() {
loaded += 1;
bar.value = loaded;
/* The below will be visible if the progress tag is not supported */
$(fallback).empty().append("HTML5 progress tag not supported: ");
$('#progUpdate').empty().append(loaded + "% loaded");
if (loaded == 100) {
clearInterval(beginLoad);
$('#progUpdate').empty().append("Upload Complete");
console.log('Load was performed.');
}
};
var beginLoad = setInterval(function() {
load();
}, 50);
});
JSFIDDLE
You might also want to try HTML5 progress element:
<section>
<p>Progress: <progress id="p" max=100><span>0</span>%</progress></p>
<script>
var progressBar = document.getElementById('p');
function updateProgress(newValue) {
progressBar.value = newValue;
progressBar.getElementsByTagName('span')[0].textContent = newValue;
} </script>
</section>
http://www.html5tutorial.info/html5-progress.php

load remote images via Javascript, then selectively add to array

Using javascript I'm trying to load images not on the current page (from an array of image links) and if they are large enough, add them to an array. I'm executing this after the current page has loaded, though a bookmarklet, or firebug console. Using FF.
The closest I've come is the below, but this does not seem to work, and I'm guessing this is because the size test is running before the images have loaded. Apparently my attempt to fix this with 'onload' does not work. How can I fix this up, or is there a better/simpler way to accomplish this task?
(function() {
//create array for the images
var imageArray = new Array();
function loadIfBig(x){
if (x.height > 299 && x.width > 299 && (x.height > 399 || x.width > 399)) {
imageArray.push(x);
//dispImage = '<img src=' + x.src + '><br>';
//document.write('<center>' + dispImage + '</center>');
}
return true;
}
//given an array of imageLinks:
for (x in imageLinks){
//create an image form link and add to array if big enough
im = document.createElement('img');
im.src = imageLinks[x];
im.onload = loadIfBig(im);
}
//view results:
for (x in imageArray){
disp_image = '<img src='+imageArray[x].src+'><br>';
document.write('<center>'+disp_image+'</center>');
}
})();
Update:
Thanks! sure you're right and I'm missing something stupid here, but I made the change you suggested, and then pulled writing the elements into loadIfBig, but it doesn't seem to be executing that function. current code below, including a couple sample input links:
(function() {
var imageArray = new Array();
var imageLinks = ['http://1.bp.blogspot.com/_mfMRTBDpgkM/SwCwu1RPphI/AAAAAAAAJpw/v9YInFBW84I/s1600/800px-San_Francisco_in_ruin_edit2.jpg','http://2.bp.blogspot.com/_mfMRTBDpgkM/SwCwulSZ_yI/AAAAAAAAJpo/NsRcJdpz4Dk/s1600/San_Francisco_PC_59.jpg']
function loadIfBig(x){
if (x.height > 299 && x.width > 299 && (x.height > 399 || x.width > 399)) {
imageArray.push(x);
dispImage = '<img src=' + x.src + '><br>';
document.write('<center>' + dispImage + '</center>');
}
return true;
}
processImages = function(){
for (x in imageLinks) {
//create an image from link and add to array if big enough
im = document.createElement('img');
im.src = imageLinks[x];
im.onload = function(){
loadIfBig(this);
}
}
}
})();
Your fix doesn't work because you're actually executing it immediately.
im.onload = loadIfBig(im) is actually running the function.
What you can do is something like:
im.onload = function() {
loadIfBig(this);
}
Another problem is the fact that you're running through the array of big images before the onload callbacks have actually executed. That needs to be stuck in a different function and called once all the onloads are done.

Categories