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>

3

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

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 ....
  }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.