jQuery not working on first click, but working with every other click

Viewed 36

I'm trying to make restaurant menu. I wrote a function, but it's not working on first click, but with every next click is ok.

jQuery(document).ready(function() {
  $("#menu-options").on('click', '#show-meat', function() {
    var clicks = $(this).data('clicks');
    if (clicks) {
      $(".menu-options-choice-veget").hide("slow");
      $(".menu-options-choice-vegan").hide("slow");
      $(".menu-options-choice-meat").animate({
        'margin-right': '-800px'
      }, 'slow');
    } else {
      $(".menu-options-choice-veget").show("slow");
      $(".menu-options-choice-vegan").show("slow");
      $(".menu-options-choice-meat").animate({
        'margin-right': '0px'
      });
    }
    $(this).data("clicks", !clicks);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="menu" id="menu-options">
  <ul>
    <li><button type="button" class="menu-otpions-button" id="show-meat">Meat</button></li>
    <li><button type="button" class="menu-otpions-button" id="show-veg">Vegetarian</button></li>
    <li><button type="button" class="menu-otpions-button" id="show-vegan">Vegan</button></li>
  </ul>
</div>

1 Answers

The issue is because there is no data-clicks attribute on the buttons when the page loads. As such when you first click a button clicks will be false, so it tries to hide the content. You need to invert this flag for the logic to work as you intend, so the element is shown on the first click:

var clicks = !$(this).data('clicks');    

Here's a full working snippet:

jQuery(document).ready(function() {
  $("#menu-options").on('click', '#show-meat', function() {
    var clicks = !$(this).data('clicks');    
    if (clicks) {
      $(".menu-options-choice-veget, .menu-options-choice-vegan").hide("slow");
      $(".menu-options-choice-meat").animate({
        'margin-right': '-800px'
      }, 'slow');
    } else {
      $(".menu-options-choice-veget, .menu-options-choice-vegan").show("slow");
      $(".menu-options-choice-meat").animate({
        'margin-right': '0px'
      });
    }
    $(this).data("clicks", clicks);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="menu" id="menu-options">
  <ul>
    <li><button type="button" class="menu-otpions-button" id="show-meat">Meat</button></li>
    <li><button type="button" class="menu-otpions-button" id="show-veg">Vegetarian</button></li>
    <li><button type="button" class="menu-otpions-button" id="show-vegan">Vegan</button></li>
  </ul>
</div>
<div class="menu-options-choice-veget">Vegetarian</div>
<div class="menu-options-choice-vegan">Vegan</div>
<div class="menu-options-choice-meat">Meat</div>

Related