Automatically loading a series of images sequentially in html - javascript

I have a html page that gets automatically refreshed every 1 ms. I did it using mata tag:
<html>
<head>
<title>My Page</title>
<meta http-equiv="refresh" content="0.001">
</head>
<body>
<img src=" 0.bmp" alt="Smiley face" height="100" width="200" />
</body>
</html>
Now my requirement is such that after every refresh I must load a new file. So in my folder I have files named: 0.bmp, 1.bmp, 2.bmp,... 1000.bmp, which will be loaded on the html file. i.e after every refresh a new file from the folder will be loaded. Basically the file name in
<img src=" 0.bmp" alt="Smiley face" height="100" width="200" />
will change from 0.bmp to 1...1000.bmp and so on.
How can we do this in html i.e change the file name dynamically?
Edited #1:
I have just realized that my problem is basically of animation. So given 1000 images stored in hard disk, I have to play them one by one on an HTML page. This should be as fast as possible. The only requirement is it must be on html pages, this is because these HTML pages will be accessed from a client in a network. the problem that I am thinking is slow playback because read/write to the disk may not be fast.
Edited # 2
After getting inputs from following answers, I was able to animate the images. The issue right now I am facing is the display rate is too small, and so fluctuations are coming up. I understand this is a problem of slow read/write from hard disk. So I guess if I can put these images in buffer i.e: System RAM, and write a html/js code to access the images from the RAM instead of the disk, the play back will be much faster. Can someone send me a sample code to, write images in RAM and use html/js code to access these images from RAM?
Note: as per the policy of stackoverflow, I am updating my question as and when I am solving various steps of the original problem.

What you are trying to do should not be done by refreshing continuously the web page, but by the use of Javascript.
Consider this method using JQUERY and setInterval():
See a working Fiddle Example!
HTML
<html>
<head>
<title>My Page</title>
</head>
<body>
<img src="path_to_image_01.jpg" alt="Smiley face" height="128" width="128" />
<img src="path_to_image_02.jpg" alt="Smiley face" height="128" width="128" />
<img src="path_to_image_03.jpg" alt="Smiley face" height="128" width="128" />
<img src="path_to_image_04.jpg" alt="Smiley face" height="128" width="128" />
</body>
</html>
JQUERY
$(document).ready(function() {
$('img:not(:first)').hide();
var refreshId = setInterval( function()
{
var $target = $('body img:first');
$target.hide().next().show();
$target.appendTo('body');
}, 1000);
});
What's being done
Hide all images
`$('img:not(:first)').hide();`
Initialize an interval of 1 sec that will collect the first image,
hide it, jump to the next image, show it, lastly move the previous
image to the end.
var refreshId = setInterval( function()
{
var $target = $('body img:first');
$target.hide().next().show();
$target.appendTo('body');
}, 1000);
This keeps on going animating the images every second that passes.

I am updating my answer based on a now different question.
You can use this plugin: https://code.google.com/p/jsmovie/ It does exactly what you want by animating a set of images.
Original Answer Below:
Although I'd agree with many of the other answers, it seems the OP needs to refresh the entire window instead of doing this via ajax without a page reload.
<img src="" alt="Smiley face" height="100" width="200" style="display:none" />
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
var imgIndex = 0;
$(document).ready(function() {
if (getParameterByName("index")!='') {
imgIndex = parseInt(getParameterByName("index"));
}
$('img').attr('src', imgIndex + '.bmp').show();
var refreshId = setInterval( function()
{
imgIndex++;
location.href = location.pathname + "?index=" + encodeURIComponent(imgIndex);
}, 1000); // 1 second update as needed
});
The following fiddle demonstrates this though I dont' have a serial set of images so the jsfiddle is a little different in that it updates an index of already set images forked from a previous answer but it does demonstrate the page reload.
http://jsfiddle.net/smf9w/1/
​

DON'T, really DON'T do this!!
Use JS instead. Use setInterval() and use a time span greater than 1m...

As others say, this is not the way to do it. But you can use cookie or localstorage on modern browsers.
function getData() {
var c = 0;
if ("localStorage" in window && null !== window.localStorage)
c = localStorage.count;
else {
count = document.cookie.split("count=");
c = c[1].split(";");
c = c[0];
}
return c;
}
function updateData(count){
if ("localStorage" in window && null !== window.localStorage)
localStorage.count = count;
else {
var e = new Date;
e.setTime(e.getTime() + 31536E6);
e = e.toGMTString();
document.cookie = "count=" + count + "; expires=" + e + "; path=/"
}
}
var count = getData();
document.write('<img src="'+ count +'".bmp" alt="Smiley face" height="100" width="200" />');
updateData(++count);
Code above is just a sample.

Related

I need assistance on this JavaScript image display code

This is the code I am currently working with: I need to display a starting image (preferably green) and then, every time the button is clicked, the image needs to change to trafficlight and then to the other image which it didn't start as. e.g it needs to go from green to orange then red then back to orange etc.
<!DOCTYPE html/>
<html>
<script type="text/javascript">
var trafficlight = [];
trafficlight [0] = " http://4vector.com/i/free-vector-traffic-light-green- clip-art_117820_Traffic_Light_Green_clip_art_medium.png ";
trafficlight [1] = "http://www.clker.com/cliparts/8/1/7/4/11949849782053089133traffic_light_yellow_ dan_01.svg.med.png ";
trafficlight [2] = "http://www.clker.com/cliparts/1/f/a/2/11949849771043985234traffic_light_red_dan_ge_01.svg.med.png ";
var num = 0;
function changepic()
{
if (num>=trafficlight.length-1){
num=0;
}
num=num+1;
document.trafficlight.src=trafficlight[num];
}
</script>
</head>
<body>
<center>
<img src ="http://4vector.com/i/free-vector-traffic-light-green-clip- art_117820_Traffic_Light_Green_clip_art_medium.png" name="trafficlightpic" width="400" height="400" />
<p>click here</p>
</center>
</body>
</html>
As noted by Jonas W - you are trying to referecnce the image but using the wrong reference. You can either do it via an id or using the name as you have. Note that if you are using the name then you need to reference it with a [0] after it as I have in the post - this is because getting the element by name will return an array like object - so you need to specify that its the first item in that. Also your image src for the orange light is broken. The folowing works and allows swapping of the src (with the exception that the yellow light image does not display).
var trafficlight = ["http://4vector.com/i/free-vector-traffic-light-green-clip-art_117820_Traffic_Light_Green_clip_art_medium.png","http://www.clker.com/cliparts/8/1/7/4/11949849782053089133traffic_light_yellow_dan_01.svg.med.png","http://www.clker.com/cliparts/1/f/a/2/11949849771043985234traffic_light_red_dan_ge_01.svg.med.png"];
function changepic()
{
var imageSrc=document.getElementsByName('trafficlightpic')[0].src;
var num =trafficlight.indexOf(imageSrc);
if (num >= trafficlight.length-1){num=-1;}
num+=1;
document.getElementsByName('trafficlightpic')[0].src=trafficlight[num];
}
<center>
<img src ="http://4vector.com/i/free-vector-traffic-light-green-clip- art_117820_Traffic_Light_Green_clip_art_medium.png" name="trafficlightpic" width="400" height="400" />
<p onclick="changepic();">click here</p>
</center>
document.trafficlight doesn't exist. You need:
document.getElementById("trafficlightpic").src=trafficlight[num];
instead. And you should change name="" to id="" in the img element. That should work.

How would I get these javascript values and use them in an image source?

My shopping cart solution passes these post-transaction variables to my thank you page's <head>...
var SecureCartOrders = [ {"orderID":237203170,"name":"asdfasdf","Total":1.00} ];
And I need them to load them in an image tracking pixel's source (to send the data to another system).
The tracking pixel is initially loaded as so...
<img id="iDev" src="" width="1" height="1" border="0">
And with a script I'm trying to set the source with those order variables...
<script>
var imgSrc = "http://www.idevaffiliate.com/32323/sale.php?profile=32&idev_saleamt=" + Total + '&idev_ordernum=' + orderID;
window.onload = function() {
document.getElementById("iDev").src=imgSrc;
}
</script>
However, my script is failing to get those variables from the script my shopping cart gives.
The result it needs to create is to set the image source with those variables like this...
<img id="iDev" src="http://www.idevaffiliate.com/32323/sale.php?profile=32&idev_saleamt=1.00&idev_ordernum=237203170" width="1" height="1" border="0">
How would I be able to do that, with the way my shopping cart lays out those variables?
Thanks :)
Based on what you said in the comments, you need to append the data to the image src variable:
var SecureCartOrders = [{
"orderID": 237203170,
"name": "Jonathan Denney",
"Total": 1.00
}];
var imgSrc = "http://www.idevaffiliate.com/32323/sale.php?profile=32&idev_saleamt=" + SecureCartOrders[0].Total + '&idev_ordernum=' + SecureCartOrders[0].orderID;
window.onload = function() {
//document.getElementById("iDev").src=imgSrc;
alert(imgSrc);
}

How to keep the current image in slideshow still the same when refresh a webpage?

On my website (http://daaamnthisisfunny.blogspot.com/) I have set up an image slide show that every time the user clicks the right arrow it will take him/her to the next picture, and do the opposite when clicks the previous arrow. The problem is when the user refresh the page it will reset the slide to the first image. What I want to make is a website like (http://9gag.com/gag/1672046) that every time the user click on the next arrow the Url of the site will change accordingly. Do you have any ideas how I can accomplish that ?
This is what i am using for my website:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<script language="JavaScript">
var NumberOfImages = 10
var img = new Array(NumberOfImages)
img[0] = "http://damnthisfunny.site40.net/1.jpg"
img[1] = "http://damnthisfunny.site40.net/2.jpg"
img[2] = "http://damnthisfunny.site40.net/3.jpg"
img[3] = "http://damnthisfunny.site40.net/4.jpg"
img[4] = "http://damnthisfunny.site40.net/5.jpg"
img[5] = "http://damnthisfunny.site40.net/6.jpg"
img[6] = "http://damnthisfunny.site40.net/7.jpg"
img[7] = "http://damnthisfunny.site40.net/8.jpg"
img[8] = "http://damnthisfunny.site40.net/9.jpg"
img[9] = "http://damnthisfunny.site40.net/10.jpg"
var imgNumber = 0
function NextImage()
{
imgNumber++
if (imgNumber == NumberOfImages)
imgNumber = 0
document.images["VCRImage"].src = img[imgNumber]
}
function PreviousImage()
{
imgNumber--
if (imgNumber < 0)
imgNumber = NumberOfImages - 1
document.images["VCRImage"].src = img[imgNumber]
}
</script>
<body>
<center>
<img name="VCRImage" src="http://damnthisfunny.site40.net/1.jpg" /></dr>
<br />
<a href="javascript:PreviousImage()">
<img border="0" src="left1.jpg" /></a>
<a href="javascript:NextImage()">
<img border="0" src="right1.jpg" /></a>
</center>
</body>
</html>
Just an idea, how about on page unload set a cookie value? May work but I'd have to test
I'd recommend using jquery for events:
http://api.jquery.com/unload/
Then for cookie parsing use
http://archive.plugins.jquery.com/project/Cookie
I'm not positive this will work
Yes you can save the current image number in the cookie. so as soon as the page loads you check for the presence of a cookie first. If there is one then you set the current image to the number in the cookie.
By the way this is all done in javascript.
Example.
var imgNumber = getCookie("lastImage") || 0;
// where getCookie is a function to retrieve cookie value
Update:
here are 2 hand functions:
// get Cookie
function getCookie(szName){
var szValue = null,
cookie = document.cookie,
arr.arr2;
if (cookie){ // only if cookie exists
arr = cookie.split((escape(szName) + '='));
if(2 <= arr.length){
arr2 = arr[1].split(';');
szValue = unescape(arr2[0]);
}
}
return szValue;
}
// set Cookie
function setCookie(szName, szValue, szExpires, szPath, szDomain, bSecure) {
var szCookieText = escape(szName) + '=' + escape(szValue),
date;
if(!szExpires) // default expiration date : 1 year
{
date = new Date();
date.setTime(date.getTime()+(365*24*60*60*1000));
szExpires = date.toGMTString();
}
szCookieText += (szExpires ? '; EXPIRES=' + szExpires : '');
szCookieText += (szPath ? '; PATH=' + szPath : '');
szCookieText += (szDomain ? '; DOMAIN=' + szDomain : '');
szCookieText += (bSecure ? '; SECURE' : '');
document.cookie = szCookieText;
}
One way is to use HTML5's replaceState method. This allows you to change the URL that is used to reload the page. This depends on the server sending the correct image in the slideshow for the given URL. Although the next and previous links would appear to link to those same URLs, you would actually call replaceState behind the scenes to avoid reloading the page.
For browsers that don't support replaceState you can still change the anchor of the URL. For browsers that support the :target CSS pseudoclass the slideshow can be written entirely in CSS. Otherwise you will need to show the correct image depending on the anchor. Some browsers provide the hashchange event which allows you to detect the user changing the anchor (e.g. by clicking back).

JS Image change won't work under other tags (should be a simple fix)

Hey guys,
basically this is my page and the JS simply changes the images if one is clicked, this works grand if the <img src='worseun.png' name='worse' border='0' /> is first beneath the <body>, but doesn't work if there is another <img src='' /> above it! I'm still learning js and this is a head wreck, can anyone suggest a fix? Heres it working with nothing above
<script type="text/javascript">
function worseChange()
{
var theImga = document.getElementsByTagName('img')[0].src;
var xa = theImga.split("/");
var ta = xa.length-1;
var ya = xa[ta];
if(ya=='worseun.png')
{
document.images.worse.src='worse.png';
document.images.cd.src='cdun.png';
}
}
function cdChange()
{
var theImgb = document.getElementsByTagName('img')[1].src;
var xb = theImgb.split("/");
var tb = xb.length-1;
var yb = xb[tb];
if(yb=='cdun.png')
{
document.images.worse.src='worseun.png';
document.images.cd.src='cd.png';
}
}
</script>
</head>
<body>
<a name=1>Uno</a>
<img src='worseun.png' name='worse' border='0' /> <br />
<img src='cd.png' name='cd' border='0' />
<a name=2>Dos</a>
<body>
Thanks guys,
James
That first line:
var theImga = document.getElementsByTagName('img')[0].src;
means, "get the very first <img> tag in the document, and then fetch its 'src' attribute value." You can instead give the "real" image an "id" value, and use document.getElementById('whatever') to get it.
<img id='worse' src='worseun.png' name='worse' border='0' />
and then
var theImga = document.getElementById('worse').src;

how to show alternate image if source image is not found? (onerror working in IE but not in mozilla) [duplicate]

This question already has answers here:
jQuery/JavaScript to replace broken images
(32 answers)
Closed 9 years ago.
I need to show an alternate image in cell of table if source image is not found.
Currently below code is used to do so.
cell.innerHTML="<img height=40 width=40 src='<%=request.getContextPath()%>/writeImage.htm' onError='ImgErrorVideo(this);'>"
function ImgErrorVideo(source){
source.src = "video.png";
source.onerror = "";
return true;
}
Now the problem is that the above is solution is working in Internet Explorer but not in mozilla.
Please tell me some solution which works in all browsers.
I think this is very nice and short
<img src="imagenotfound.gif" alt="Image not found" onerror="this.src='imagefound.gif';" />
But, be careful. The user's browser will be stuck in an endless loop if the onerror image itself generates an error.
EDIT
To avoid endless loop, remove the onerror from it at once.
<img src="imagenotfound.gif" alt="Image not found" onerror="this.onerror=null;this.src='imagefound.gif';" />
By calling this.onerror=null it will remove the onerror then try to get the alternate image.
NEW
I would like to add a jQuery way, if this can help anyone.
<script>
$(document).ready(function()
{
$(".backup_picture").on("error", function(){
$(this).attr('src', './images/nopicture.png');
});
});
</script>
<img class='backup_picture' src='./images/nonexistent_image_file.png' />
You simply need to add class='backup_picture' to any img tag that you want a backup picture to load if it tries to show a bad image.
I have got the solution for my query:
i have done something like this:
cell.innerHTML="<img height=40 width=40 alt='' src='<%=request.getContextPath()%>/writeImage.htm?' onerror='onImgError(this);' onLoad='setDefaultImage(this);'>"
function setDefaultImage(source){
var badImg = new Image();
badImg.src = "video.png";
var cpyImg = new Image();
cpyImg.src = source.src;
if(!cpyImg.width)
{
source.src = badImg.src;
}
}
function onImgError(source){
source.src = "video.png";
source.onerror = "";
return true;
}
This way it's working in all browsers.
If you're open to a PHP solution:
<td><img src='<?PHP
$path1 = "path/to/your/image.jpg";
$path2 = "alternate/path/to/another/image.jpg";
echo file_exists($path1) ? $path1 : $path2;
?>' alt='' />
</td>
////EDIT
OK, here's a JS version:
<table><tr>
<td><img src='' id='myImage' /></td>
</tr></table>
<script type='text/javascript'>
document.getElementById('myImage').src = "newImage.png";
document.getElementById('myImage').onload = function() {
alert("done");
}
document.getElementById('myImage').onerror = function() {
alert("Inserting alternate");
document.getElementById('myImage').src = "alternate.png";
}
</script>

Categories

Resources