1

I have five images in a folder of my computer and I'm trying to create a script that display an image on the screen and when I click a button the image changes.

The JavaScript code:

function cambiaimagen()
{
var i=1;
var direcciones = new            
    Array("imagen1.jpg","imagen2.jpg","imagen3.jpg","imagen4.jpg","imagen5.jpg");
var vusr = document.getElementById('imgs').value;
document.getElementById('imgs').innerHTML = vusr;
}

The HTML code:

<div id="contenedor">

<div id="img">
<img id="imgs" src="imagen1.jpg"/>
</div>

<button type="button">Anterior</button>
<button type="button" onclick = 'cambiaimagen()'>Siguiente</button>

</div>

When I run the script I watch the image 1 and the buttons. But when I click Siguiente button I don't watch the following image of array direcciones.

How can I watch it?

0

2 Answers 2

1

Replace your previous JavaScript code with this:

var cnt = 1;
var direcciones = new Array("imagen1.jpg","imagen2.jpg","imagen3.jpg","imagen4.jpg","imagen5.jpg");
function cambiaimagen(){
    if(cnt != direcciones.length - 1){
        cnt++;
    }else{
        cnt = 1;
    }
    document.getElementById('imgs').src = direcciones[cnt];
}

If the image names are in sequential number order (as they are in your example), you could use the following instead:

var cnt = 1;
var imgCnt = 5;
function cambiaimagen(){
    if(cnt != imgCnt){
        cnt++;
    }else{
        cnt = 1;
    }
    document.getElementById('imgs').src = "imagen" + cnt + "2.jpg";
}

Which I believe is a better method because there is no array with repetitive contents.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm using Firefox and there are no JavaScript errors. Wnen I run the script I only watch the image and the buttons. When I click one button the image doesn't change.
Yes. Now it works. I was typed the code wrongly. Thanks for the answer.
1
var direcciones = ["imagen1.jpg","imagen2.jpg","imagen3.jpg","imagen4.jpg","imagen5.jpg"];
var cnt = 0;
function cambiaimagen(){
document.getElementById("imgs").src = direcciones[(++cnt)%direcciones.length];
}

2 Comments

You should probably explain what you're doing, rather than just post code.
I think it's just one more way of doing the answer anyone else would give.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.