I'm calling a random image from flickr api.
now it's working but user need to wait for image to download,
how can I do a preload of next image so user will see the image right away.
I need to preload just the next image each time,this is my code:
$(document).ready(function(){
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
//tags: keyword,
tagmode: "any",
format: "json"
});
var loadNewImage = function() {
var rnd = Math.floor(Math.random() * data.items.length);
var image_src = data.items[rnd]['media']['m'].replace("_m", "_b");
$('.main').css('background-image', "url('" + image_src + "')");
}
var imageInterval = 10000;
setInterval(loadNewImage(), imageInterval);
});
One way would be to insert a hidden img into the document and handle its onload event.
Related
I have the following HTML in my project.
<div class="container" id="crop">
<img id="timage" src="http://example.com/color/style/etc/" alt="timages" />
I also have the following javascript:
$(window).load(function () {
$("#slider").change(function update() {
sVal = $(this).val();
if (sVal == 2) {
$('#timage').prop('src',"http://example.com/" +
tForm +
"color.blahblah" +
itemCode +
"therest_ofthe_URL");}
sVal = $(this).val();
if (sVal == 3) {
$('#timage').prop('src',"http://example.com/" +
tForm +
"color.blahblah" +
itemCode +
"therest_ofthe_URL");}
);}
It works splendidly to replace the image with the string when the slider value reaches certain numbers. The problem is, the image is being created on the back end behind the scenes and takes quite some time before it is ready. In the meantime, you are just staring at the original image wondering if the slider did anything.
How do I add a loading indicator to let people know that the image is about to change?
First, place a loading indicator where you want it. You could replace #timage with a spinning gif, for example. Then use this code to start the new image loading:
var img = new Image();
img.onload = function () {
$('#timage').prop('src', img.src);
}
img.src = '/image/to/load/here';
The function will be executed when your new image has been retrieved from the server and loaded. Since it's already cached on the client, it should load instantly once the src for #timage is set.
I want to show a remote image on my page. I use Bootstrap 2.3.2 Carousel. All the information comes from another web site's RSS feed. I get data into a div like the following:
...
<div id="newsItem-<?php echo $i;?>" class="item" data-src="<?php echo $feed[$i]->image; ?>" data-alt="<?php echo $feed[$i]->title; ?>">
</div>
...
The images takes too long to load. Page is loaded about 15 seconds. So I have decided to load images after the page loading finished.
There could be various dimensions of the pictures to be displayed.
I want to show the largest existing one.
For each news item, all the images may have different but similar dimensions such as 1024x768, 620x350, 528x350, 527x350.
I have written a jQuery script to achieve this but something is wrong.
jQuery(function () {
jQuery("div[id^='newsItem-']").each(function () {
var r = jQuery(this).attr("data-src");
var r620 = r.replace(".jpg", "-620x350.jpg");
var r527 = r.replace(".jpg", "-527x350.jpg");
var r1024 = r.replace(".jpg", "-1024x678.jpg");
var r528 = r.replace(".jpg", "-528x350.jpg");
var altImg = jQuery(this).attr("data-alt");
if (pictureExists(r1024)){
r = r1024;
}
else if (pictureExists(r620)){
r = r620;
}
else if (pictureExists(r528)){
r = r528;
}
else if (pictureExists(r527)){
r = r527;
}
jQuery(this).prepend("<img src='" + r + "' alt='" + altImg + "' />");
jQuery(this).removeAttr("data-alt");
jQuery(this).removeAttr("data-src");
});
});
function pictureExists(url) {
var img = new Image();
img.src = url;
if (img.height !== 0) {
return false;
} else {
return true;
}
}
I want to display the largest existing picture in the carousel.
You cannot know the height/width of the image until its loaded. So its an async process.
In pictureExists function try to do it in this way:
/ Create new image
var img = new Image();
// Create var for image source
var imageSrc = "http://example.com/blah.jpg";
// define what happens once the image is loaded.
img.onload = function() {
// Stuff to do after image load ( jQuery and all that )
// Within here you can make use of src=imageSrc,
// knowing that it's been loaded.
};
// Attach the source last.
// The onload function will now trigger once it's loaded.
img.src = imageSrc;
If you want to use the above way then you will have to implement promise structure to tackle the async nature of the image load to fetch the height/width
Or you can use this small plugin.
https://github.com/desandro/imagesloaded
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
I am making a photo gallery using jQuery and I want to have a button to display a random picture taken from the ones in the album. This picture should change every time the user clicks on the button. I have this code but every time I press the button I have the div#images fulling with the images instead of each one every time.
<script>
$('button').on('click', function() {
$.getJSON('images.json', function(data) {
imageList = data;
});
$('#images').append('<img src=' + imageList[Math.floor(Math.random() * imageList.length) + 1].img_src + '>').;
});
</script>
As you can see I read the images from a JSON file and randomize from 1 to the length of the file. Any suggestions would be helpful. Thank you in advance.
You need to clear the image div before adding the new image otherwise the images will keep adding.
<script>
$('button').on('click', function() {
$.getJSON('images.json', function(data) {
imageList = data;
//Also, move the code inside getJson(). getJson is asynchronous.
//Clear the images HTML
$('#images').empty();
$('#images').append('<img src=' + imageList[Math.floor(Math.random() * imageList.length) + 1].img_src + '>').;
});
});
</script>
Just wondering : Why don't you retrieve 1 random image via json call, instead of fetching all the images and then choosing one (Write the randomization code at the server) ?
Does the JSON data change? Otherwise, why do a request everytime? Separating the rand and image vars below isn't necessary, but might be easy to read for others later.
$('button').on('click', function() {
if ( typeof imageList == 'undefined' || !imageList.length )
{
$.getJSON('images.json', function(data) {
imageList = data;
var rand = Math.floor(Math.random() * imageList.length) + 1;
var image = $('<img />').attr('src', imageList[ rand ].img_src );
$('#images').html( image );
});
}
else
{
var rand = Math.floor(Math.random() * imageList.length) + 1;
var image = $('<img />').attr('src', imageList[ rand ].img_src );
$('#images').html( image );
}
});
Make sure you close the image tag as well as clear the existing image
<script>
$('button').on('click', function() {
$.getJSON('images.json', function(data) {
imageList = data;
});
$('#images').html("");
$('#images').append('<img src=' + imageList[Math.floor(Math.random() * imageList.length) + 1].img_src + '/>');
});
</script>
I'm trying to get an user input image to refresh say every two seconds. The javascript gets user input for an URL and the javscript adds it to the page. Then the images loaded need to refresh every 2 seconds but i can't get it to refresh properly without refreshing the whole page or reloading from the cache:
function getImg(){
var url=document.getElementById('txt').value;
var div=document.createElement('div');
div.className="imageWrapper";
var img=document.createElement('img');
img.src=url;
div.appendChild(img);
document.getElementById('images').appendChild(div);
return false;
}
setInterval(function(){
$('img').each(function(){
var time = (new Date()).getTime();
$(this).attr("src", $(this).attr("src") + time );
});
}, 2000);
any ideas?
When you need to force reload the resource, you have to add a dymmy queryString at the end of your url:
<img id="img1" src="myimg.png?dummy=23423423423">
Javascript:
$('#img1').attr('src','myimg.png?dummy=23423423423');
and change the dummy value for each refresh
Your premise seems good, not sure why it isn't working. Why mixing and matching jQuery with non-jquery? This is a modification of your code, but it is a working example. You should be able to adapt it for your purpose.
http://jsfiddle.net/zr692/1/
You can create elements via jQuery easily. See the modified getImg function I created. Ia also switched from attr to prop which is the recommended means of accessing the src attribute in jQuery 1.7+.
function getImg() {
var url = 'http://placehold.it/300x300/123456';
var $div = $('<div />');
var $img = $('<img />', { src: url });
$div.append($img);
$('body').append($div);
}
getImg();
var interval = setInterval(function() {
$('img').each(function() {
var time = (new Date()).getTime();
var oldurl = $(this).prop('src');
var newurl = oldurl.substring(0, oldurl.lastIndexOf('/') + 1) + time.toString().substr(7, 6);
$('#output').html(newurl);
$(this).prop('src', newurl);
});
}, 2000);
Put the image in a container as:
<div id="container"><img src=""../> </div>
then simply update the content of the container as:
$('#container').html('<img src="newSource"../>');