3

We have a list of paired divs dynamically built in a ColdFusion page (internshipHandleX, internshipHiddenX, etc.) by looping over a query and adding the current row, eg:

<div id="internshipHidden#internship.currentrow#" class="hidden pop-up">

that we want to bind together as modal windows and corresponding triggers. Using this code:

for (var row = 1; row <= totalInternships; row ++){
    var thisHandle = "#internshipHandle" + row;
    var thisHidden = "#internshipHidden" + row;
    $(thisHandle).click(function(e){
        e.preventDefault();
        $(thisHidden).bPopup({modalColor:"black"});
    });
}

We apparently link all of the internshipHandle(s) to the last internshipHidden. What am I missing? Is there a better way to make modal windows out of dynamically created css-hidden divs (that is, within the skeleton framework? I REALLY don't want to start over using bs.)

DreamWeaver is not happy about me putting functions in loops but all the cool kids tell me not to listen to it.

Edit:tryed the same thing with the jqueryUI dialog and had the same problems. I'd love an explanation. Thanks!

Maxhirez
  • 99
  • 7
  • Do you have your javascript code wrapped in `$( document ).ready()` so that it does not execute until the DOM has been loaded? You probably need to show us more code as what you have is not a complete example. – Miguel-F Jan 20 '16 at 13:58

1 Answers1

1

Welcome to Javascript. You just encountered a closure in its natural habitat.

In order to have the row variable working the way you expect it to, you need to pass it in its own scope. This can be done using a closure. You may want to dig deeper into that topic, but for now, here is a fix for your problem:

var totalInternships = 2;

for (var row = 1; row <= totalInternships; row++){
    var bindInternship = function(rowIndex) {
     $("#internshipHandle" + rowIndex).click(function(e){
          e.preventDefault();
          alert('pop-up #' + rowIndex);
          //$("#internshipHidden" + rowIndex).bPopup({modalColor:"black"});
        });
    };
    bindInternship(row);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<button type="button" id="internshipHandle1">pop-up 1</button>
<div id="internshipHidden1" class="hidden pop-up">

<button type="button" id="internshipHandle2">pop-up 2</button>
<div id="internshipHidden2" class="hidden pop-up">

Note: I commented the line for the bPopup. Uncomment it, remove the alert and you're good to go.

Community
  • 1
  • 1
Alex
  • 7,743
  • 1
  • 18
  • 38