I'm working on a Javascript example about click events which are generated in a for loop.
<?php
$pages=$i/2;
for($k=1;$k<=$pages;$k++){
echo '<div style="border: 1px solid; width: 15px; display: inline-block" id="page-'.$k.'">'.$k.'</div>';
}
?>
<div id="dom-pages" style="display: none;" class="<?= $pages?>"></div>
<script>
var tag = document.createElement("script");
tag.src = "../web/js/pagination.js";
document.getElementsByTagName("head")[0].appendChild(tag)
</script>
This is the HTML part where i generate divs depending on the number of $pages variable. The important part is that each div id will be "page-'.$k.'" From page-1 to page-'$pages'
The pagination.js script loaded is:
var div = document.getElementById("dom-pages");
var stranice = div.className;
var element=[];
for(var i=0;i<stranice;++i){
element[i] = document.getElementById("page-"+(i+1));
var margin=-40*i;
$(element[i]).click(function() {
$('#page-slider').css({
'margin-top': margin
})
});
}
The script gets the $pages value over var 'div' and is stored in var 'stranice' Using the array 'element' all the wanted Id values are genereated. From "page-1" to "page-$pages". Each Id css margin-top should be changed on click, starting from the id=page-1/margin-top=0 to the last id=page-$pages/-40*$pages.
All divs and Ids are generated as wanted, the only problem is that all the generated id click events have the margin-top value of -40*$pages not each individual -40*i counter of the for loop. I can't figure out why all the click events & margin/margin-top value get the value of the last for loop run. I'd appreciate if someone could help me with this. Thanks!