0

I try to create function that allows have a different number of pairs "popup"/"opener-button". Every opener-button should open appropriate popup. But it doesn't work and I can't understand why. Please help me find the source of the problem and advice solutions to have result that I want see.

Problem: http://jsfiddle.net/f4kc2a84/4/

Script:

function InitPopupOpener(options) {
    if (options.opener.length == options.popup.length) {
        for (var i = 0; i < options.opener.length; i++) {
            var opener = '.' + options.opener[i];
            var popup = '.' + options.popup[i];
            console.log(opener);
            $(opener).click(function (event) {
                $(popup).toggle();
            });

            $(document).click(function (event) {
                if ($(event.target).closest(popup).length == 0 && $(event.target).attr('class') != opener.substr(1)) {
                    $(popup).hide();
                }
            });
        }
    }
}

Now it works only for second popup.

AlexAstanin
  • 343
  • 1
  • 4
  • 14

1 Answers1

1

The problem is that the variables popup and opener will be the same for all the anonymous functions you create; they'll be left as whatever they are at the end of the for loop. (This is because of how Javascript scope works.)

What you need is to introduce another anonymous function to act as a scope for each invocation of the for loop:

function InitPopupOpener(options) {
    if (options.opener.length == options.popup.length) {
        for (var i = 0; i < options.opener.length; i++) {
            (function(opener, popup) {
                console.log(opener);
                $(opener).click(function (event) {
                    $(popup).toggle();
                });

                $(document).click(function (event) {
                    if ($(event.target).closest(popup).length == 0 && $(event.target).attr('class') != opener.substr(1)) {
                        $(popup).hide();
                    }
                });
            })('.' + options.opener[i], '.' + options.popup[i]);
        }
    }
}

You can see this in action here (jsfiddle), which I believe does what you require.

Community
  • 1
  • 1
James Aylett
  • 3,332
  • 19
  • 20