0

I want the button with the class name of "x-1" to give the div with the class name of "popup-1" a display property of "none". and "x-2" gives the div "popup-2" a display of "none" when clicked. i have tried this and when i press "x-1" it gives a display of "none" to "popup-2" instead of "popup-1".

$(document).ready(function(){
   var xCount = 2;
   for (i = 0; i < xCount; i++) {
      $('.x-'+i).click(function(){
         $('.popup-'+i).css('display','none');
      });
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="x-1">Hide popup-1</button>
<button class="x-2">Hide popup-2</button>

<div class="popup-1">popup-1</div>
<div class="popup-2">popup-2</div>
Saadi Toumi Fouad
  • 2,779
  • 2
  • 5
  • 18
vape bees
  • 3
  • 3
  • It is a problem of closures, so `i` should be declared using the `let` keyword to avoid getting into closures – Saadi Toumi Fouad Oct 04 '20 at 05:46
  • This is a good question about closures: https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – A_A Oct 04 '20 at 05:49
  • Does this answer your question? [JQuery loop function only works on last element](https://stackoverflow.com/questions/11800943/jquery-loop-function-only-works-on-last-element) – Akif Oct 04 '20 at 06:17

2 Answers2

3

your loop defines an i variable in global scope. so when you click on button, i is already mutated better define i with let keyword to avoid closure problem. here is rectification of your code.

$(document).ready(function() {
  var xCount = 2;
  for (let i = 1; i <= xCount; i++) {
    $('.x-' + i).click(function() {
      $('.popup-' + i).css('display', 'none');
    });
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="x-1">Hide popup-1</button>
<button class="x-2">Hide popup-2</button>

<div class="popup-1">popup-1</div>
<div class="popup-2">popup-2</div>
sandeep joshi
  • 1,991
  • 1
  • 8
  • 13
0

Firstly adding click events to loop is not good practise.

Now answer to your question you have two button added click by id separating with comma. Here is something you can try.

$('.x-1,.x-2').click(function(){
var className = this.className;
  if(className === 'x-1')
  {
  ... do something ....
  }
  else
  {
  ... do something ....
  }
});
Abhishek Borikar
  • 374
  • 1
  • 5
  • 15