0

I have the folowing functions :

function showPoster(element,list_nr) 
{ 
    var image ="url('../Login/" + movie_image[list_nr] + "'), auto";
    element.style.cursor = image;
}

function putNewContent(page)
{
    for(var i = 1; i <= 10; i++)
    { 
        document.getElementById("p"+i+1).onmouseover = function() { showPoster(this,(page-1)*10+i); }
    }
} 

The problem is that when,for example,i run putNewContent(1) , it will call the function showPoster() 10 times, but the argument which arrives to showPoster() is always 11 (i<=10),so it finishes the for first,i gets to 11,and then it calls the function. How can i send the parameter i correctly ?(the list_nr argument to be the same as the i in the for as it gets evaluated).

Halvor Holsten Strand
  • 19,829
  • 17
  • 83
  • 99
c0mm0s0r3
  • 3
  • 1

1 Answers1

0

The problem is that your index (i) is declared outside the function and not private to each instance. All functions ends up using the last one, 10 in your case.

This can be solved with .bind()

function putNewContent(page) {
  for (var i = 1; i <= 10; i++) {
    document.getElementById("p" + i + 1).onmouseover = function(i) {
      showPoster(this, (page - 1) * 10 + i);
    }.bind(null,i)
  }
}

Or closures

function putNewContent(page) {
  for (var i = 1; i <= 10; i++) {
    document.getElementById("p" + i + 1).onmouseover = (function(i) {
        return function() {
          showPoster(this, (page - 1) * 10 + i);
        }
      }
    })(i);
}

Both will keep a private instance of i for each function.

Magnus Engdal
  • 5,446
  • 3
  • 31
  • 50