jQuery won't load updated images - javascript

Is anyone able to determine, how to stop the jQuery caching the image that it grabs, and displaying the same image around and around again?
Basically the image is been re-uploaded every 5 seconds, as it acts as a webcam (if you check the time stamp on the bottom right of the image, you can tell if it's been updated or not)
http://colourednoise.co.uk/scripts/index.htm
Thank you
(sorry I forgot to hit paste for the code)
$(function(){
$(document).ready(function() {
var imgs = ['http://www.ramseycommunityradio.co.uk/images/webcam.jpg', 'http://www.ramseycommunityradio.co.uk/images/webcam.jpg']
$("#webcam").attr('src', imgs[1]);
var refreshId = setInterval(function() {
$("#webcam").fadeOut("slow", function() {
var $el = $(this);
$el.attr('src', $.inArray($el.attr('src'), imgs) === 0 ? imgs[1] : imgs[0]);
$el.fadeIn("slow");
});
}, 2000);
});

You could try appending a changing query string onto the URL, this should stop caching if that is indeed your problem. I've seen this done with a time stamp here: how to generate and append a random string using jquery
So each time you generate an image you do:
var qs = (new Date).getTime();
var url = 'http://www.example.com/images/myimage.jpg?' + qs;
$(el).attr('src',url);

your code:
var imgs = ['http://www.ramseycommunityradio.co.uk/images/webcam.jpg', 'http://www.ramseycommunityradio.co.uk/images/webcam.jpg']
$("#webcam").attr('src', imgs[1]);
var refreshId = setInterval(function() {
$("#webcam").fadeOut("slow", function() {
var $el = $(this);
$el.attr('src', $.inArray($el.attr('src'), imgs) === 0 ? imgs[1] : imgs[0]);
// this condition is redundant, it will ultimately give the same result always
// because imgs[0]==imgs[1]
$el.fadeIn("slow");
});
}, 2000);
as far a JQuery is concerned you are not changing the SRC attribute (JQuery knows nothing about the content of the image). Try using two different names in the server-side like webcam0.jpg and webcam1.jpg and alternating between them.

One trick is t append a random query string URL which causes the image to reload from the server. The code could be something like:
setInterval(function() {
var img = $("#img").get(0);
img.src = img.src.replace(/\?.*/, "") + "?" + Math.random();
}, 5000);

Related

Problems using next() and prev() methods for cyclic gallery - javascript / jQuery

I'm new to javascript and jQuery. I'm trying to create an online gallery to see photos, using 2 buttons "next" and "prev". It must be cyclic so, for example, if I click "next" when the last photo is displayed, the next photo must be the first one.
I tried to use 3 variables: first img, last img and current img, so that I just need to do currimg = currimg.prev() (or next). And, for example, if the img displayed is the first one, I do currimg = lastimg.
$(document).ready(function() {
$("img").wrapAll("<div></div>");
$("img").nextAll().hide();
var firstimg = $("img:first");
var lastimg = $("img:last");
var currimg = firstimg;
$("#nextbutton").click(function(){
currimg.fadeOut("fast", function(){
(currimg==lastimg) ? currimg=firstimg : currimg=currimg.next();
currimg.fadeIn("fast");
});
});
$("#prevbutton").click(function(){
currimg.fadeOut("fast", function(){
(currimg==firstimg) ? currimg=lastimg : currimg = currimg.prev();
currimg.fadeIn("fast");
});
});
});
The problem is that the cycle works only if I press firstly prev. If I click next and then twice prev, it doesn't work and it shows nothing. Where is the problem?
The problem with your solution is that every time you assign to your currimg the values returned from currimg=currimg.next(); or currimg.prev(); you are assigning a new jQuery object.
This causes that when you make the comparison (currimg==firstimg) this will not be true even if both currimg and firstimg are pointing to the same DOM element.
In order to check if two jQuery objects point to the same DOM element you can use the is method.
So, your code should look something like:
$(document).ready(function() {
var $imgs = $("img");
$imgs.wrapAll("<div></div>");
$imgs.nextAll().hide();
var firstimg = $imgs.first();
var lastimg = $imgs.last();
var currimg = firstimg;
$("#nextbutton").click(function(){
currimg.fadeOut("fast", function() {
currimg = (currimg.is(lastimg)) ? firstimg : currimg.next();
currimg.fadeIn("fast");
});
});
$("#prevbutton").click(function(){
currimg.fadeOut("fast", function(){
currimg = (currimg.is(firstimg)) ? lastimg : currimg.prev();
currimg.fadeIn("fast");
});
});
});
Note that I have also stored all your images in $imgs so that there is no need to do multiple selections of the images on your script startup. The use of the ternary operator has also been changed in order to be clearer/cleaner.

Running a javascript animation followed by redirecting

So I'm fiddling with a fun idea for an offline website I'm currently trying to develop.
It'll be offline as it's meant to be practice for later study assignments and such.
My problem is the following: I have a javascript function that replaces a PNG with a GIF and after the animation it should redirect the person to another html I've made.
The source for the JS animation is mainly acquired from here already, but I cannot seem to make it work in the ways I originally intended.
The way it currently works is that I click the png and it'll turn into a gif (no problem there) but what I want is that it runs my js script and then redirect to another .html file (url).
The following is my HTML:
<object id="syringe">
<img src="img/syringe.png" height="750" alt="img/syringe.gif" class="center">
<h2>Click the syringe to inject yourself with a daily dose of puns and jokes</h2>
</object>
The following is the JS:
(function($) {
var getGif = function() {
var gif = [];
$('img').each(function() {
var data = $(this).data('alt');
gif.push(data);
});
return gif;
}
var gif = getGif();
var image = [];
$.each(gif, function(index) {
image[index] = new Image();
image[index].src = gif[index];
});
$('#syringe').on('click', function() {
var $this = $(this),
$index = $this.index(),
$img = $this.children('img'),
$imgSrc = $img.attr('src'),
$imgAlt = $img.attr('data-alt'),
$imgExt = $imgAlt.split('.');
if($imgExt[1] === 'gif') {
$img.attr('src', $img.data('alt')).attr('data-alt', $imgSrc);
} else {
$img.attr('src', $imgAlt).attr('data-alt', $img.data('alt'));
}
$this.toggleClass('play');
});
})(jQuery);
It is to my understanding that I can add a delay and then another function to something in the js - such as the following, which is what I intend to do, however cannot accomplish.
[FUNCTION HERE],1000,
function(){
window.location.href=myredirectionuri;
});
And that is my problem.
It looks like you want to have the gif display for a second or two and then redirect, right? If $this.toggleClass('play'); is the end, then just insert this right after it:
setTimeout(() => window.location.href = myredirectionuri, 1000);
That'll wait for 1000ms and then redirect to the new page.
In the animation script, after it changes to a gif, insert
setTimeout(function() {
/* redirect code */
}, /* length of gif in milliseconds */ )

Dynamically change image in javascript

JavaScript Noob here.
I want to show the dynamically changing image effect like this:
http://dotsignals.org/google_popup.php?cid=202
(if this webpage cannot show changing image, click on any camera at http://dotsignals.org)
I have examined the code, and have some questions:
1.The website uses setImage and refreshSetImage to initialize and refresh the image for a dynamically changing effect. What is the use of Math.random in here? I understand it is a way to differentiate images from different time at the same cam. But how does it works? How would the backend respond?
2.Related to the first question. What is the mechanism of the refreshSetImage? I didn't see any sign of requesting data from the server. Does it send a "GET"? How does it refresh the image?
function setImage(imageID){
var currentImage = imageID;
document.getElementById(currentImage).src ='http://207.251.86.238/cctv9.jpg'+'?math=';
refreshSetImage();
}
function refreshSetImage() {
document.images["myCam"].src = 'http://207.251.86.238/cctv9.jpg'+'?math='+Math.random();
setTimeout('refreshSetImage()',1000);
}
function ScaleSize(imageID) {
var elem = document.getElementById(imageID);
elem.style.width = 500;
elem.style.height = 300;
}
3.How is the backend designed?
4.Now I want to use these two functions in my own project. I want to add a parameter of camID in the setImage and refreshSetImage functions, so the src of the image will change to something like: 'http://..../'+camID+'.jpg'+'?math'. camID is a String that identifies different cameras. I changed it to:
function refreshSetImage(camID) {
document.images["myCam"].src = 'http://207.251.86.238/'+camID+'.jpg'+'?math='+Math.random();
setTimeout('refreshSetImage(camID)',1000);
}
function setImage(imageID,camID){
var currentImage = imageID;
document.getElementById(currentImage).src = 'http://207.251.86.238/'+camID+'.jpg'+'?math=';
refreshSetImage(camID);
}
and got an error :Uncaught ReferenceError: camID is not defined VM132:1. The image is not changing as well. I don't know what is the problem. What is VM132:1 ?
Thanks
check
function refreshSetImage(imageID,camID) {
currentImage = imageID;
url = 'http://207.251.86.238/'+camID+'.jpg'+'?math='+Math.random();
//document.getElementById(currentImage).src= url;
console.log(url);
}
$(document).ready(function(){
imageID = "imageID";
camID = "camID";
setInterval(function() {
refreshSetImage("imageID","camID");
}, 3000);
});
https://jsfiddle.net/Cuchu/vr1ftwg1/

Load content in div from a href tag in jQuery

I want to load all images before displaying them in a slideshow. I have been searching a lot but nothing seems to work. This is what i have so far and it doesn't work. I am loading images from the <a> tag from another div.
$('.slideshow').load(function(){
if (loaded<length){
first = $(settings.thumb).eq(loaded).find('a').attr("href");
$('<img src="'+first1+'"/>').appendTo('.slideshow');
}
else{ $('.slideshow').show(); }
loaded++;
});
Add an event listener to each image to respond to when the browser has finished loading the image, then append it to your slideshow.
var $images = $("#div_containing_images img");
var numImages = $images.length;
var numLoaded = 0;
var $slideshow = $(".slideshow");
$images.each(function() {
var $thisImg = $(this);
$thisImg.on("load", function() {
$thisImg.detach().appendTo($slideshow);
numLoaded++;
if (numLoaded == numImages) {
$slideshow.show();
}
});
});
It's a good idea to also listen for the error event as well, in case the image fails to load. That way you can increase numLoaded to account for broken image. Otherwise, your slideshow will never be shown in the event the image is broken.
Also note, that by calling detach() followed by appendTo() I am am moving the image in the DOM. If instead, you want to copy the image, use clone() instead of detach().
* EDIT TO MODIFY USER'S EXACT USE CASE *
var $images = $("li.one_photo a");
var numImages = $images.length;
var numLoaded = 0;
$images.each(function() {
$('<img />',
{ src: $(this).attr("href") })
.appendTo('.slideshow')
.on("load error", function() {
numLoaded++;
if(numLoaded == numImages) {
$('.slideshow').show();
}
});
});
* EDIT #2 *
Just realized you were putting everything in the $(".slideshow").load() function. Since $(".slideshow") represents a DIV, it will never raise a load event, and the corresponding function will never execute. Edited above accordingly.

Display Image Based on URL Ending (Variable or Attribute) [Pound/Number Sign # ]

I need an image to be displayed based on the ending of a URL.
For example, I need "123.jpg" to be displayed when someone visits:
website.com/view/#123
website.com/view/#123.jpg
website.com/view#123
website.com/view#123.jpg
(whichever is recommended or would actually work)
I'm looking for the end result to be: < img src=123.jpg" >
Thanks in advance. I will sincerely appreciate any assistance.
(By way of background or additional information, I need this for Facebook's sharer.php so that people can share one of hundreds of images on a given webpage (for example, website.com/blog and they happen to love the 123rd image on there), they click the link to share that specific image (123.jpg), and then any of their friends who clicks on the link (website.com/view/#123) will arrive at a themed page with just the image in the middle (123.jpg) and nothing else, and then they can click around the rest of the website. The main benefit is that 123.jpg will be the only image that shows up as a thumbnail on the Facebook Feed or "Wall".)
window.onhashchange = function() {
if (location.hash) {
var url = location.hash.substr(1); // strip the # char
if (url.indexOf('.') == -1) {
url += '.jpg';
}
document.getElementById('myImg').src = url; // show the image; value of the variable 'url'
}
};
window.onhashchange(); // call the event on load
Use something like this.
$(document).ready(function(){
var url = document.URL; //get the url
if ( url.indexOf("#") != -1 ) //check if '#' is present in the url
{
var split_array = url.split("#");
var image_url = split_array[split_array.length - 1];
//display the image
}
});
Try this out,
$(document).ready(function() {
getImageSrc();
$(window).on('hashchange', getImageSrc); // will always lookout for changes in # URL
});
function getImageSrc() {
if(window.location.hash) {
var imgSrc = window.location.hash.substr(1);
if(imgSrc.indexOf('.') == -1 ) {
imgSrc = imgSrc + ".jpg";
}
alert(imgSrc);
}
}

Categories

Resources