0

What I am trying to do is to set the same function to different elements with similar id, for example "icon-1","icon-2","icon-3". The function opens up a window that corresponds to those ids -- "window-1", "window-2","window-3". I was trying to use this code block:

for (var i=1; i<=3; i++) {
  $("#icon"+i.toString()).click(function(){
      $("#window"+i.toString()).show();
   )};
)};

Ideally, when "icon-1" is clicked, it opens "window-1", etc. But it's not working.

And I checked console.log(i), every time when a click event occurs, it prints out the final count of i, which is 4.

Is there any way to fix or walk around this?

Thanks a lot!

benjaminz
  • 3,118
  • 3
  • 35
  • 47

3 Answers3

0

When you say 'opens up a window', do you mean to open up a popup window or just showing an existing element?
Assuming it's the latter, I would give each of your icons a class that they all share and attach the click handler to elements with that class rather than using three different click handlers. Then use the data attribute to store the corresponding window number:

<div class="icon" data-window="1">This is an icon</div>
<div class="icon" data-window="2">This is an icon</div>

$('.icon').click(function(){
    var windowNum = $(this).data();
    $('#window-' + windowNum).show();
});
maembe
  • 1,270
  • 1
  • 13
  • 25
0

Try classes to achieve that.

$('.yourIconClass').each(function() {
    $(this).click(function(){
        $('.yourWindowClass').eq($(this).index).show();
    });
});
-1

I wouldn't use a for loop for this. I don't use query, so I'll speak in javascript.

I would assign the buttons/icons to variables in javascript and then just have an event listener for each of the buttons. That event listener will send a value to a function that will determine which window to open:

var button1 = document.getElementById("button_1_id");
var button2 = document.getElementById("button_2_id");
var button2 = document.getElementById("button_2_id");

button1.addEventListener('click',function(){
    triggerWindow(1);
});
button2.addEventListener('click',function(){
    triggerWindow(2);
});
button3.addEventListener('click',function(){
    triggerWindow(3);
});

function triggerWindow(input) {
    if(input === 1){
     /* code to trigger window one */
    }
    else if(input === 2){
     /* code to trigger window two */
    }
    else if(input === 3){
     /* code to trigger window three */
    }
}
Sam Eaton
  • 1,795
  • 1
  • 14
  • 19