Niklas Wagner
Niklas Wagner

Reputation: 23

Have to click twice to trigger onclick button

I have to click 2 times on my onclick-button to trigger it for the first time. After the first 2 clicks, the button works as expected.

Here is my code:

var cv3 = document.getElementById("gallerycanvas");
var context03 = cv3.getContext("2d");
var buttonnext = document.getElementById("buttoncanvasnext");

var myImages = [
    'Skins/MonkeyKing_0.jpg',
    'Skins/MonkeyKing_1.jpg',
    'Skins/MonkeyKing_2.jpg',
    'Skins/MonkeyKing_3.jpg',
    'Skins/MonkeyKing_4.jpg',
    'Skins/MonkeyKing_5.jpg',
    'Skins/MonkeyKing_6.jpg'
];
var img = document.createElement("img");
var i = 0;
img.setAttribute('src', myImages[i])

img.onload = function() {
    context03.drawImage(img, 0, 0);

    if (i >= myImages.length) {
        i = 0;
    }

    buttonnext.onclick = function() {    
        img.setAttribute('src', myImages[i++]);
        context03.drawImage(img, 0, 0);
    }
}

Can you help me? Thank you!

Upvotes: 2

Views: 361

Answers (3)

benjamin c
benjamin c

Reputation: 2338

When you use i++ to increase i, the value will be returned before the operand is increased.

Change buttonnext.onclick function to,

buttonnext.onclick = function() {
  i++;
  img.setAttribute('src', myImages[i]);
  context03.drawImage(img, 0, 0);
}

And to make image loop work when keep clicking on button, do following changes,

img.onload = function() {
    context03.drawImage(img, 0, 0);

    buttonnext.onclick = function() {
       if (i >= myImages.length - 1) {
          i = 0;
       } else {
          i++;
       }
       img.setAttribute('src', myImages[i]);
       context03.drawImage(img, 0, 0);
   }
}

Upvotes: 0

mikewoe
mikewoe

Reputation: 270

Use ++i instead of i++

To feel difference just use both in console alert.

++i (pre) increment before using variable

i++ (post) increment after

Upvotes: 1

Nimitt Shah
Nimitt Shah

Reputation: 4587

Problem is in your onclick method. You are using i++ in the array

buttonnext.onclick = function() {
  img.setAttribute('src', myImages[i++]);
  context03.drawImage(img, 0, 0);
}

Instead, use i++ before setting the image src;

buttonnext.onclick = function(){
   i+=1;
   img.setAttribute('src', myImages[i]);
   context03.drawImage(img,0,0);
}

Thanks

Upvotes: 0

Related Questions