JavaScript Timed Image Swap Need Help - javascript

So in my script I have...
<script type="text/javascript">
var images = new Array();
var numImages = 3;
var index = 0;
function setupSwapper() {
for (i = 0; i < numImages; i++) {
images[i] = new Image(266, 217);
images[i].src = "images/image" + i + ".png";
}
setTimeout("swapImage()", 5000);
}
function swapImage() {
if (index >= numImages) {
index = 0;
}
document.getElementById('myImage').src = images[index].src
index++;
setTimeout("swapImage()", 5000);
}
</script>
And then I have <body onload="setupSwapper()"> to setup the body.
and <img width=266 height=217 id="myImage" name="myImage" src="images/image0.png"></img> elsewhere in my document.
Only the initial image (image0.png) is showing up. I'm probably blind from having looked at this so long. The images are not swapping.

Use FireBug or a similar tool for debugging what's going on:
Does the img DOM element in fact gets its src changed ?
Do you see any network activity trying to load the images ? does it succeed ?
Set up breakpoints in your code and see what happens in the debugger
BTW - You can use setInterval instead of setTimeout - it sets a repeating timer

You're missing the () in the definition of "setupSwapper".
Also it's setTimeout, not setTimeOut.
Finally, get rid of the "type" attribute on your <script> tag.
You might want to start "index" at 1 instead of 0.

The way to go:
setTimeout(swapImage, 5000);
[FORGET] the type attribute has nothing to do with it
[FORGET] the index has nothing to do with it
[OPTIONAL] remove "name" attribute from the image (useless)
[OPTIONAL] close image tags like <img />
Note: 2-5 is about correctness. Only the first one is important to get it work.

Get Firebug, use it's debugger to put breakpoints inside swapImage to see if it is hit after the timeout. Another way is to use the console.* apis to see what's happening(e.g. console.log).

Related

javascript/html: Second onclick attribute

I have an image - image1.png. When I click a button the first time, I want it to change to image2.png. When I click the button for a second time, I want it to change to another image, image3.png.
So far I've got it to change to image2 perfectly, was easy enough. I'm just stuck finding a way to change it a second time.
HTML:
<img id="image" src="image1.png"/>
<button onclick=changeImage()>Click me!</button>
JavaScript:
function changeImage(){
document.getElementById("image").src="image2.png";
}
I'm aware I can change the image source with HTML within the button code, but I believe it'll be cleaner with a JS function. I'm open to all solutions though.
You'll need a counter to bump up the image number. Just set the maxCounter variable to the highest image number you plan to use.
Also, note that this code removes the inline HTML event handler, which is a very outdated way of hooking HTML up to JavaScript. It is not recommended because it actually creates a global wrapper function around your callback code and doesn't follow the W3C DOM Level 2 event handling standards. It also doesn't follow the "separation of concerns" methodology for web development. It's must better to use .addEventListener to hook up your DOM elements to events.
// Wait until the document is fully loaded...,
window.addEventListener("load", function(){
// Now, it's safe to scan the DOM for the elements needed
var b = document.getElementById("btnChange");
var i = document.getElementById("image");
var imgCounter = 2; // Initial value to start with
var maxCounter = 3; // Maximum value used
// Wire the button up to a click event handler:
b.addEventListener("click", function(){
// If we haven't reached the last image yet...
if(imgCounter <= maxCounter){
i.src = "image" + imgCounter + ".png";
console.log(i.src);
imgCounter++;
}
});
}); // End of window.addEventListener()
<img id="image" src="image1.png">
<button id="btnChange">Click me!</button>
For achieve your scenario we have to use of counter flag to assign a next image. so we can go throw it.
We can make it more simple
var cnt=1;
function changeImage(){
cnt++;
document.getElementById("image").src= = "image" + cnt + ".png";
}
try this
function changeImage(){
var img = document.getElementById("image");
img.src = img.src == 'image1.png' ? "image2.png" : "image3.png";
}
Just use an if statement to determine what the image's source currently is, like so:
function changeImage(){
var imageSource = document.getElementById("image").src;
if (imageSource == "image1.png"){
imageSource = "image2.png";
}
else if (imageSource == "image2.png"){
imageSource = "image3.png";
}
else {
imageSource = "image1.png";
}
}
This should make the image rotate between 3 different image files (image1.png, image2.png and image3.png). Bear in mind this will only work if you have a finite number of image files that you want to rotate through, otherwise you'd be better off using counters.
Hope this helps.
Check the below code if you make it as a cyclic:
JS
var imgArray = ["image1.png", "image2.png", "image3.png"];
function changeImage(){
var img = document.getElementById("image").src.split("/"),
src = img[img.length-1];
idx = imgArray.indexOf(src);
if(idx == imgArray.length - 1) {
idx = 0;
}
else{
idx++;
}
document.getElementById("image").src = imgArray[idx];
}
html
<button onclick=changeImage();>Click me!</button>
function changeImage(){
document.getElementById("image").attr("src","image2.png");
}

How can we make Image Carousel with background Image Property

I'm making an image carousel i'm bounded to use background-image property instead of using
<img src="Image">
tag. my carousel is working if I use img tag . But its not working when I use background-image property, how can I modify my code with background-image property.
see my fiddle :https://jsfiddle.net/korLasen/ and update it please thanks :)
or you can see code here
(function(){
var image = $('#imageSlider');
var imageSet = ['http://www.exposureguide.com/images/top-ten-tips/top-ten-photography-tips-1e.jpg','http://images.clipartpanda.com/cliparts-images-aTqyrB8TM.png'];
var index = 0;
function imageSliderSet(){
image.setAttribute('data-background', imageSet[index]);
index++;
if(index >= imageSet.length){
index = 0;
}
}
setInterval = (imageSliderSet, 2000);
})();
This is quite a strange question... however, I am not one to judge :)
Here is a jsfiddle based on your example. I ended up using jquery for this. I hope this is somewhere near what you were looking for!
This is based on changing every two seconds. To extend that, you can change line 18 in the jquery. Here is the jquery:
$( document ).ready(function(){
var image = $('#imageSlider');
var imageSet = ['http://www.exposureguide.com/images/top-ten-tips/top-ten-photography-tips-1e.jpg','http://images.clipartpanda.com/cliparts-images-aTqyrB8TM.png'];
var index = 0;
window.setInterval(function(){
image.css('background-image', "url('" + imageSet[index] + "')");
index++;
if(index >= imageSet.length){
index = 0;
}
//here you can adjust the time interval for each photo
}, 2000);
});

Changing a picture by clicking on it with Javascript

This is my first ever question on here and I figure it must have a simple answer but it's frustrated me for a while, especially since I'm new to Javascript. So I have many images and would like to change to the next one by clicking on it on the webpage, starting with a certain image, obviously. Now I could do this with nested if else statements but if you have many images you get too many ones nested into each other and it can get too complex so I figured there must be a simpler way of doing it. Here's an example of the code I had:
function changeImage()
{
var image=document.getElementById("mainImage")
if (image.src.match("image1.jpg"))
{
image.src="image2.jpg";
}
else if (image.src.match("image2.jpg"))
{
image.src="image3.jpg";
}
else
{
if (image.src.match("image3.jpg"))
{
image.src="image4.jpg";
}
else
{
image.src="image1.jpg";
}
}
}
So you can see it's not the best way to do it. I tried to do it with a switch statement but I couldn't either (and would appreciate it if someone told me if it could be done with one and how). As a last try I tried this but for some reason it jumps from image1 to image4 at once:
function changeImage()
{
var images = ["image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg"]
var myImage = document.getElementById("mainImage")
for (i=0; i < images.length; i++)
{
if (myImage.src.match(images[i]))
{
myImage.src = images[i+1]
}
}
}
So I could really appreciate some help. Thanks in advance.
Your last changeImage goes to #4 immediately because you're changing the image in the for loop which causes the check within the loop to keep being true and so it runs all the way to the last index, at which point the check finally fails. Instead, you'll want to maintain the current image index with a variable. Then, just change myImage.src to images[currentIndex + 1] on each click. Try something like below. You'll want to run showNextImage on page load and then run it once each time the image is clicked.
<script>
var currentImageIndex = 0;
//Cycle through images
showNextImage() {
var images = ["image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg"]
var myImage = document.getElementById("mainImage")
myImage.src = images[currentImageIndex];
currentImageIndex++;
if(currentImageIndex >= images.length)
currentImageIndex = 0;
}
</script>

Chrome doesn't always repeat events with JavaScript setInterval()

I want to display several images of the same size at the same position, one at a time, with a 5s interval between each change. To do so I've used jQuery.Timer, that uses setInterval() to call some show_next_image() function every 5s.
It actually does work with IE, Opera, Safara, Firefox and.. partly with Google Chrome. It's not working with Google Chrome if I open a new window and directly type my website URL: it'll show the second image and stop. And with any other situation (reload, from another link, not right after opening a new window) it'll badly work: one can see the back image before the front image is shown.
Thus I'm wondering whether I've done something wrong with my JavaScript source. What I do is I use a front and a back image. When I want to show the next image, the back img source is set to the new image, and the front image is faded out while the back one is faded in through jQuery. You can check it out at http://www.laurent-carbon.com/ (in French). The two img are identified with bg1 and bg2.
var images = ["/img/IMG_0435bg.jpg", "/img/IMG_0400bg.jpg", "/img/maisonnette 2.jpg", "/img/IMG_0383bg.jpg", "/img/IMG_0409bg.jpg", "/img/IMG_0384bg.jpg"];
var idx = 1;
var waitTime = 5000; // ms
$(document).ready(function() {
$("#bg2").hide();
$.timer(waitTime, load_next);
$.preLoadImages(images);
});
function load_next(timer) {
var toshow = images[idx];
idx++;
idx %= images.length;
back_image().attr('src', toshow);
swap_images();
}
function front_image() {
return (idx % 2 == 0) ? $("#bg1") : $("#bg2");
}
function back_image() {
return (idx % 2 == 0) ? $("#bg2") : $("#bg1");
}
function swap_images() {
back_image().fadeOut('slow');
front_image().fadeIn('slow');
}
Thanks,
Ceylo
Ok I've worked out a solution .... without the use of plugins.
Demo
http://jsfiddle.net/morrison/PvPXM/9/show
source
http://jsfiddle.net/morrison/PvPXM/9/
This approach is a lot cleaner and removes the problem I had while viewing your page in chrome: the animation getting out of sync and flashing.
The only thing you have to do in the HTML is wrap the two images in a <div id="fadeBox" style="position:relative"></div>
$(function() {
var images = [
"http://www.laurent-carbon.com/img/IMG_0435bg.jpg",
"http://www.laurent-carbon.com/img/IMG_0400bg.jpg",
"http://www.laurent-carbon.com/img/maisonnette 2.jpg",
"http://www.laurent-carbon.com/img/IMG_0383bg.jpg",
"http://www.laurent-carbon.com/img/IMG_0409bg.jpg",
"http://www.laurent-carbon.com/img/IMG_0384bg.jpg"
];
var idx = 1;
var max = images.length;
var easing = "swing";
var waitTime = 5000; // ms
var fadeTime = 2000; // ms
var fadeShow = function(fadeTime, fadeDelay) {
var $topImage = $("#fadeBox img:last");
$topImage.fadeTo(fadeDelay, 1, function() {
$topImage.fadeTo(fadeTime, 0, easing, function() {
$topImage
.fadeTo(0, 1)
.insertBefore("#fadeBox img:first")
.attr("src", images[++idx == max ? idx = 0 : idx]);
fadeShow(fadeTime, fadeDelay);
});
});
};
fadeShow(fadeTime, waitTime);
});
Hope this helps
PS thanks to Levi for cleaning the code up a bit.
Answer: http://jsfiddle.net/morrison/RxyZY/
Notes:
You are trying to reinvent the wheel. You are creating a simple slideshow. There are numerous plugins to do exactly this and much more. I used jQuery cycle in my example, which is extremely customizable.
You should wrap your stuff up in a function, creating an expression. In my example, the (function($){}(jQuery)) is what does the trick. It scopes your variables to the function, rather than the global namespace.

Dynamically changing images in a div

I've five images and would like to display it in a same div one by one with interval of 2 sec. Can anyone please suggest any solution for this?
Simple javascript example:
var currentImage = 0;
var images = [
'a.jpg',
'b.jpg'
];
var imageElement = document.getElementById('yourImageTagId');
function nextImage(){
currentImage = (currentImage + 1) % images.length;
imageElement.src = images[currentImage];
}
var timeoutId = setTimeout(nextImage, 1000);
It expects you to have some html like this:
<img src="a.jpg" id="yourImageTagId" />
Jquery Cycle is really flexible... you could hook it up to whatever youve got already marked up pretty easily.
There are many ways to do this nowadays but one simple way is using the following jquery plugin:
http://jquery.malsup.com/cycle/
Here is a simple demo in action fading images one after the other.
http://jquery.malsup.com/cycle/basic.html
setTimeout
You can do something like this.
function selectData(currentIndex) {
// select current's element "display" to "none" and show next element
...
// schedule next change in two second
setTimeout("selectData(" + nextIndex + ");", 2000);
};
I assume all images are inside that div already and have style display:none

Categories