0

Is it possible to use the current value of a variable when defining a javascript function? In the following code I'd like to add a click function to an array of divs, each with a different value for i, ie. the first div should call setCurrentStyleIndex(0). At the moment they all call whatever the value of i is at the time of the call.

Sorry if this is dumb question.

Step3.populateStyleMenu = function() {
    var stylePopup = $("#stylePopup");
    for(var i = 0; i < Step3.fontStyles.length; i++) {
        var div = $('<div>'+Step3.fontStyles[i][0]+'</div>');
        div.css({
            'font-weight': Step3.fontStyles[i][1],
            'font-style': Step3.fontStyles[i][2],
        })
        div.data('style', Step3.fontStyles[i]);
        div.addClass('personalizePopupItem personalizeStyleItem');


        div.click(function() {
            setCurrentStyleIndex(i);
        });


        stylePopup.append(div);
     }
}
0

2 Answers 2

2

try to create a closure (not tested):

(function (i) {
    div.click(function() {
        setCurrentStyleIndex(i);
    });
})(i);
Sign up to request clarification or add additional context in comments.

Comments

1

Yup, you can do the below:

div.click((function() {
  var inx = i;
  return function() {
    setCurrentStyleIndex(inx);
  }
})());

Comments

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.