0

i created a very simple toggle function. I have 6 div-Tags with individual id's and 6 a-Tags Why i can't use the loop-variable to iterate through the id's?

<script>
    var open = false;
    var boxes = document.getElementsByClassName("boxlink");

    for (var i = 0; i < boxes.length; i++) {

          boxes[i].addEventListener("click", function () {

                    var b = document.getElementById("textbox" + i);
                    toggle(b);
                }

                , false);

    }

    function toggle(obj) {


        if (open == false) {

            obj.style.height = 'auto';
            open = true;

        }
        else {

            obj.style.height = '78px';
            open = false;
        }

    }


</script>

1 Answers1

0

You have to create a closure in the loop

// Code goes here

var open = false;
var boxes = document.getElementsByClassName("boxlink");

for (var i = 0; i < boxes.length; i++) {


  var onClickFunction = (function(i) {
    return function() {

      var b = document.getElementById("textbox" + i);
      toggle(b);
    }
  })(i);
boxes[i].addEventListener("click",onClickFunction , false);

}

function toggle(obj) {


  if (open == false) {

    obj.style.height = 'auto';
    open = true;

  } else {

    obj.style.height = '78px';
    open = false;
  }

}
Vladu Ionut
  • 8,075
  • 1
  • 19
  • 30
  • Wonderful, thank you very much! The only thing i don't understand is the last (i)-expression after the function – Ben Böhlke Jan 22 '17 at 15:50
  • Immediately-Invoked Function Expression (IIFE) http://benalman.com/news/2010/11/immediately-invoked-function-expression/ – Vladu Ionut Jan 22 '17 at 16:20
  • Thank you! Just one more question: On this page: http://kolleritsch.benjaminboehlke.com/projects.html When you click on "WEITERLESEN" the first time nothing happen. When you click again the code works well. This problem affects every "WEITERLESEN"-link. Why? – Ben Böhlke Jan 23 '17 at 09:55