0

Trying to get the numerical value of the current button that's being called from an array so I can display an image and description from another array based on bNames array number.

i doesn't seem to work. Trying to get images[i] and descriptions[i] to show based on the numerical value of bNames.

var bNames = ["#button01","#button02","#button03"];
var images = ["image01.png","image02.png","image03.png"];
var descriptions = ["And a one","And a two", "And a three"];


for (var i=0; i<bNames.length; i++){
$(bNames[i]).click(function(e) { 
    $("#image").html("<img src=images/" + images[i] + " />");
    $("#desc").html(descriptions[i]);
});
}

Any help is greatly appreciated, thanks!

user1320948
  • 21
  • 1
  • 6

2 Answers2

0

The problem you are having is described in this question. Also see JavaScript loop closures for more information. Essentially, you are always using the last value that is held by i.

Something like this should do the trick:

for (var i=0; i<bNames.length; i++) {
    (function(index) {
        $(bNames[index]).click(function(e) { 
            $("#image").html("<img src=images/" + images[index] + " />");
            $("#desc").html(descriptions[index]);
        });
    })(i);
}

Also from that question, you could do this instead:

$.each(bNames, function(i, item) {
    $(item).click(function(e) {
        $("#image").html("<img src=images/" + images[i] + " />");
        $("#desc").html(descriptions[i]);
    });
});
Community
  • 1
  • 1
nick_w
  • 14,758
  • 3
  • 51
  • 71
0

NOTE: Never ever define a function inside a loop...

You are in the world of HTML5 its a revolution... Use data attributes... Heres the solution...

HTML:

  <button class="button" data-index="0">Button01</button>
  <button class="button" data-index="1">Button02</button>
  <button class="button" data-index="2">Button03</button>
  <div id="image"></div>
  <div id="desc"></div>

Javascript:

var images = ["image01.png","image02.png","image03.png"];
var descriptions = ["And a one","And a two", "And a three"];


$(".button").click(function(){
  var i = $(this).data("index");
  $("#image").html("<img src=images/" + images[i] + " />");
  $("#desc").html(descriptions[i]);
});
Sandeep
  • 2,041
  • 21
  • 34