Image display based on time - javascript

I'm trying to create an image rotator that displays certain images at certain times, but also rotates at other times in the day.
When I first created it, I just had it rotate every three seconds. That worked fine. But once I added the code to make a different image show up at different times, it quit working all together. Part of the problem is I'm confused about where I should put the setInterval and clearInterval. Anyway, here;s the code.
<img id="mainImage" src="/arts/rotatorpics/artzone.jpg" />
JS:
var myImage = document.getElementById("mainImage");
var imageArray = ["arts/rotatorpics/artzone.jpg",
"arts/rotatorpics/bach.jpg",
"arts/rotatorpics/burns.jpg"];
var imageIndex = 0;
var changeImage = function() {
mainImage.setAttribute("src", imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
var newDay = new Date(); //create a new date object
var dayNight = newDay.getHours(); //gets the time of day in hours
function displayImages() {
if (dayNight >= 10 && dayNight <= 12) {
mainImage.setAttribute("src", imageArray[1]);
} else if (dayNight >= 17 && dayNight <= 19) {
mainImage.setAttribute("src", imageArray[2]);
} else {
var intervalHandle = setInterval(changeImage, 3000);
}
myImage.onclick = function() {
clearInterval(intervalHandle);
};
}​

first of all, all your variables seem to be are global, please dont do that, use an anonymous function-wrapper which executes your code (immediately (read about IIFE here. this is not part of your problem, but just good and clean coding style.
(function() {
// your code here
})();
then i think one of your problems is your displayImages-function, which you declare but never call!
just should call it at the end of your code (or just leave it out)
displayImages();
if you want your images not to be swapped between 10-12 and 17-19 your code should then work as expected. if the images should swap even at this times, you shouldnt put the setInterval into the last else (inside your displayImages-function

Related

Problems Cycling through Images with JavaScript

I am currently having a problem with my function not correctly cycling through images. The first image I have in the html code will show, but the code attempts to switch to a second image but instead just shows the blank white background. All images lie in the same directory folder. I have checked and made sure all file names and extensions match the their true names, attempted to find any syntax errors that might be causing this not to run but to no avail. could it be the fact that I am attempting to create an array and populate it at the same time, but doing so incorrectly?
Here is the answer I based my code off of: Link
Here's my current relevant code:
JS:
<script type="text/javascript">
function displayNextImage() {
var i = (i === imgArray.length - 1) ? 0 : i + 1;
document.getElementById("image").src = imageArr[i];
}
function displayPreviousImage() {
var i = (i <= 0) ? imgArray.length - 1 : i - 1;
document.getElementById("image").src = imageArr[i];
}
function startTimer() {
setInterval(displayNextImage, 2000);
}
var imageArr = ["~/Images/Carrying Food In.jpg", "~/Images/Food Pantry.jpg", "~/Images/Fresh Produce.jpg", "~/Images/Handing Out Food.jpg", "~/Images/Man Pushing Wheelbarrow.jpg", "~/Images/Woman Leading Class.jpg"], i = -1
</script>
Relevant HTML:
<body onload="startTimer()">
<img id="image" src="~/Images/Food Pantry.jpg" style="width: auto;" />
<p></p>
</body>
Edit: Changed one method to previous (had two of the same method names) - problem still persists
That's because of misspelled reference to your array and because on every function run you redeclare iterator variable var i. This code should work:
<script type="text/javascript">
var imageArr = ["~/Images/Carrying Food In.jpg", "~/Images/Food Pantry.jpg", "~/Images/Fresh Produce.jpg", "~/Images/Handing Out Food.jpg", "~/Images/Man Pushing Wheelbarrow.jpg", "~/Images/Woman Leading Class.jpg"], i = -1
var i;
function displayNextImage() {
i = (i <= 0) ? imageArr.length - 1 : i - 1;
document.getElementById("image").src = imageArr[i];
}
function startTimer() {
setInterval(displayNextImage, 2000);
}
</script>

Refresh a DIV content after faded it out

I got X DIV (TopRowRight1, TopRowRight2, TopRowRight3...) , each containing a different Google Geochart generated by a php page : GeochartPerProvince.php?template=X.
function getResult(template){
jQuery.post("GeochartPerProvince.php?template="+template,function( data ) {
jQuery("#TopRowRight"+template).html(data);
});
}
jQuery().ready(function(){
getResult(1);
setInterval("getResult(1)",10000);
getResult(2);
setInterval("getResult(2)",10000);
getResult(3);
setInterval("getResult(3)",10000);
});
jQuery(function () {
var $els = $('div[id^=TopRowRight]'),
i = 0,
len = $els.length;
$els.slice(1).hide();
setInterval(function () {
$els.eq(i).fadeOut(function () {
i = (i + 1) % len
$els.eq(i).fadeIn();
})
}, 5000)
});
Every 5 seconds, i fade out one and fade in the next one. This works perfectly.
For now, the php page in the DIV is refreshed every 10 seconds. This works too.
But what i dream about is that the php page in the DIV is reloaded AFTER the DIV is faded out instead of every 10 seconds. How to do it?
Solved. How it works properly:
function getResult(template){
jQuery.post("GeochartPerProvince.php?template="+template,function( data ) {
jQuery("#TopRowRight"+template).html(data);
});
}
$(document).ready(function(){
getResult(0);
getResult(1);
getResult(2);
//setInterval("getResult(2)",10000); <== keep this piece of code in case of need.
});
$(document).ready(function () {
var $els = $('div[id^=TopRowRight]'),
i = 0,
len = $els.length;
$els.slice(1).hide();
setInterval(function () {
$els.eq(i).fadeOut(function () {
i = (i + 1) % len
getResult(i);
$els.eq(i).fadeIn();
})
}, 10000)
});
You're already using a callback function after the element has been faded out. So why not call your getResult function inside it?
$el.fadeOut(function(){
// stuff
getResult(i)
})
I have a few suggestions and an example code for you to achieve what you need :
Use $ instead of jQuery for easier reading / writing
$(document).ready is the proper start point for dom related functions
If only one div is visible at a time, do not use too many divs. Most of the time one div is enough for alternating / refreshing content. If there is in/out animation or cross-fading, two divs would be needed. (Example below uses two divs)
Avoid using setInterval except you really really need. Logics with setTimeout better handles unexpected delays such $.post may cause.
start with html code something like this:
...
<div class="top-row-right" style="display:block"></div>
<div class="top-row-right" style="display:none"></div>
...
js:
$(document).ready( function() {
var len = 4; // 'I got X DIV..' This is where we put the value of X.
var template = -1;
function refreshChart() {
template = (template + 1) % len;
$.post("GeochartPerProvince.php?template="+template, function(data) {
var offscreenDiv = ('.top-row-right:hidden');
var onscreenDiv = ('.top-row-right:visible');
offScreenDiv.html(data);
onScreenDiv.fadeOut('slow', function() {
offScreenDiv.fadeIn();
setTimeout(refreshChart, 10000);
});
});
}
refreshChart();
});

Loop images on hover - setInterval issue

My code is running well...
but there is one thing I can't solve:
when I mouseover the image the loop starts well, but on subsequent mouseovers it starts changing faster and faster...
var Image = new Array("//placehold.it/400x180/?text=Welcome",
"//placehold.it/400x180/?text=To",
"//placehold.it/400x180/?text=My",
"//placehold.it/400x180/?text=Web+page",
"//placehold.it/400x180/?text=INPHP");
var Image_Number=0;
var Image_Length= Image.length;
function change_image(num){
Image_Number = Image_Number + num;
if(Image_Number > Image_Length)
Image_Number = 0;
if(Image_Number < Image_Length)
document.slideshow.src = Image[Image_Number];
return false;
Image_Number = Image_Length;
}
function auto () {
setInterval("change_image(1)", 1000);
}
<img src="//placehold.it/400x180/?text=Welcome" name="slideshow" onmouseover="auto()" />
On every mouseover you're reassigning a brand-new-intervalâ„¢ resulting in multiple functions running at the same time.
name on IMG tag is an obsolete HTML5 attribute - See also img tag # W3.org
"change_image(1)" ...strings inside setInterval or setTimeout tigger eval. Which is bad. The real function name should be used instead: setInterval(functionName, ms)
You're not managing well the argument num
You cannot have code after a return statement
Use the mouseenter event (instead of mouseover)
and many more errors....
Here's a remake:
var images = [
"//placehold.it/400x180/?text=Welcome",
"//placehold.it/400x180/?text=To",
"//placehold.it/400x180/?text=My",
"//placehold.it/400x180/?text=Web+page",
"//placehold.it/400x180/?text=INPHP"
];
var c = 0; // c as Counter ya?
var tot = images.length;
var angryCat = false;
// Preload! Make sure all images are in tha house
for(var i=0; i<tot; i++) {
var im = new Image();
im.src= images[i];
}
function changeImage() {
document.slideshow.src = images[++c%tot];
}
function auto() {
if(angryCat) return; // No more mouse enter
angryCat = true;
setInterval(changeImage, 1000);
}
<img src="//placehold.it/400x180/?text=Welcome" name="slideshow" onmouseenter="auto()" />
The increment and loop is achieved using ++c % tot
The angryCat boolean flag helps to know it the auto() already started (mouse was there!), in that case it will return; (exit) the function preventing the creation of additional overlapping intervals on subsequent mouseenter (which was your main issue).
Additionally, I'd suggest to keep your JS away from HTML, so instead of the JS attribute event
onmouseenter="auto()"
assign an ID to your image id="myimage" and use JS:
document.getElementById("myimage").addEventListener("mouseenter", auto, false);

Getting images to change in a for loop in javascript

So far I created an array with 11 images, initialized the counter, created a function, created a for loop but here is where I get lost. I looked at examples and tutorial on the internet and I can see the code is seeming simple but I'm not getting something basic here. I don't actually understand how to call the index for the images. Any suggestions. Here is the code.
<script type="text/javascript">
var hammer=new Array("jackhammer0.gif",
"jackhammer1.gif",
"jackhammer2.gif",
"jackhammer3.gif",
"jackhammer4.gif",
"jackhammer5.gif",
"jackhammer6.gif",
"jackhammer7.gif",
"jackhammer8.gif",
"jackhammer9.gif",
"jackhammer10.gif")
var curHammer=0;
var numImg = 11;
function getHammer() {
for (i = 0; i < hammer.length; i++)
{
if (curHammer < hammer.length - 1) {
curHammer = curHammer +1;
hammer[i] = new Image();
hammer[i].src="poses/jackhammer" +(i+1) + ".gif";
var nextHammer = curHammer + 1;
nextHammer=0;
{
}
}
}
}
setTimeout("getHammer()", 5000);
</script>
</head>
<body onload = "getHammer()";>
<img id="jack" name="jack" src = "poses/jackhammer0.gif" width= "100" height ="113" alt = "Man and Jackhammer" /><br/>
<button id="jack" name="jack" onclick="getHammer()">Press button</button>
Following on what Paul, said, here's an example of what should work:
var hammer=["jackhammer0.gif","jackhammer1.gif","jackhammer2.gif","jackhammer3.gif",
"jackhammer4.gif","jackhammer5.gif","jackhammer6.gif","jackhammer7.gif",
"jackhammer8.gif","jackhammer9.gif","jackhammer10.gif"];
var curHammer=0;
function getHammer() {
if (curHammer < hammer.length) {
document.getElementById("jack").src= "poses/" + hammer[curHammer];
curHammer = curHammer + 1;
}
}
setTimeout("getHammer()", 5000);
The big missing element is that you need to call getElementById("jack") to get a reference to the DOM Image so that you can change it's source. If you're using jQuery or most other JS frameworks, just type $("#jack") to accomplish the same.
I don't understand the need for the for loop at all, just increment the index value [curHammer] each time you click, and reset if it passes your max index length (in this case 11).
Pseudo-Code:
currentHammer = -1
hammers = [ "a1.jpg", "a2.jpg", "a3.jpg"]
getHammer()
{
currentHammer = currentHammer + 1;
if(currentHammer > 2)
currentHammer = 0;
image.src = hammers[currentHammer];
}
a) are you just trying to show an animated gif? If so, why not use Adobe's Fireworks and merge all those gifs into a single gif?
b) you know that the way you have it the display is going to go crazy overwriting the gif in a circle right?
c) you might want to put a delay (or not). If so, make the load new gif a separate function and set a timeout to it (or an interval).
Also, you are being redundant. How about just changing the src for the image being displayed?:
var jackHammer = new Array();
for (var i=0;i<11;i++) { //pre-loading the images
jackHammer[i] = new image();
jackHammer[i].src = '/poses/jackHammer'+i.toString()+'.gif';
} //remember that "poses" without the "/" will only work if that folder is under the current called page.
for (var i=0;i<11;i++) { //updating the image on
document.getElementById('jhPoses').src = jackHammer[i].src;
}
on the document itself,
< img id='jhPoses' src='1-pixel-transparent.gif' width='x' height='y' alt='poses' border='0' />

setInterval() not working after clearInterval() in this Javascript code

I have been ripping my hair off a couple of nights now with this problem:
I'm trying to create an expanding div with JavaScript. Here's the part of the HTML file:
<div id="bbc_div" class="bbc_div" style="display:none; height:200px;">
<input type="button" value="Show BBC" id="bbc_button" onclick="onclickBBC('bbc_div')" />
And here's the magical non-working JavaScript file:
var maxHeight = 100;
var curHeight = 1;
var wait = 5;
var timerID = new Array();
function onclickBBC(obj) {
if (document.getElementById(obj).style.display == "none") {
slideDown(obj);
}
else {
document.getElementById(obj).style.display="none"
}
}
function slideDown(obj) {
document.getElementById(obj).style.height="1px";
document.getElementById(obj).style.display="block";
timerID[obj] = setInterval("slideDownExec(\"" + obj + "\")", wait);
return;
}
function slideDownExec(obj) {
if (curHeight <= maxHeight) {
curHeight++;
document.getElementById(obj).style.height=curHeight + "px";
}
else {
endSlide(obj);
}
return;
}
function endSlide(obj) {
clearInterval(timerID[obj]);
return;
}
When I reload the page, div expands once to its right height. But, if I push the button without reloading page again after it has hided again, it doesn't work. display:block; works, but setInterval() isn't starting. So this happens after clearInterval() has executed. Why is clearInterval() killing my setInterval() permanently?
The timer is running, you just need to reset a variable:
function slideDown(obj)
{
document.getElementById(obj).style.height = "1px";
curHeight = 1;
I would use jQuery for this, it's a LOT easier.
You have an issue with curHeight not being set to 1 at the top of slideDown. If this doesn't happen, the if statement at the top of slideDownExec will only work the first time.
Additionally, does JavaScript allow non-integer array indexes?
> a['i'] = 4
4
> a
[]
> a['i']
4
What you're actually doing is adding a property called i to the array object. You might as well use an empty object rather than an array.

Categories

Resources