Why my jquery toggle class does not work with a single click

advertisements

I am using a jquery function for toggle effect for an icon so when I click on that icon the div will move to left and hide.. so only the icon will show on the page and when I click on that icon again the div will appear sliding from left I am able to achieve the function but the following function

$(document).ready(function() {
  $(".demo-icon").click(function() {
    if ($('.demo_changer').hasClass("active")) {
      $(".demo_changer").animate({
        "left": "-208px"
      }, function() {
        $('.demo_changer').toggleClass("active");
      });
    } else {
      $('.demo_changer').animate({
        "left": "0px"
      }, function() {
        $('.demo_changer').toggleClass("active");
      });
    }
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="demo_changer" style="padding-top:13px">
  <div class="demo-icon customBgColor">
    <i class="fa fa-bullhorn fa-spin fa-2x"></i>
  </div>
  <div class="form_holder">
    <div class="row">
      <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
        <div class="predefined_styles">
          <div class="skin-theme-switcher">
            <a href="campaign.html" target="_blank">
              <h4>some text</h4>
            </a>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

Thanks for any replies in advance.


Just found out that you did not add the class active while pageload but yet displaying the div.

Change the below line

<div class="demo_changer" style="padding-top:13px">

as

<div class="demo_changer active" style="padding-top:13px">

While loading, your webpage shows the div but does not have the class active in the div tag and while clicking for the first time, as per your script, it finds out that there is no active class in the tag and then adds the class active and your div is already visible... I hope you understood..


The issue may be that, the margin in <div class="row"> is overlapping the icon div, it might be a reason why clicking on that area does not trigger "click" event -- See image below

Try Adding css style as mentioned in image below -