danny244
danny244

Reputation: 11

ToggleClass overlap

I'm trying to use the same button to open and close a menu, I'm sure this is super simple but I'm new to the world of jQuery. I'm using the Wordpress builder 'Oxygen' if that helps. Here's my code:

The modal is an in-built feature in the website builder so I can't provide much code on that. It's basically set to trigger when element with class "open" is clicked, and close with element class "oxy-modal-close".

jQuery

jQuery("#toggle").click(function () {
jQuery('#plus').toggleClass('rotate');
jQuery('#toggle').toggleClass('open oxy-modal-close');
});

HTML

<div id="toggle" class="open">
   <img id="plus" src="http://hausse.co.uk/wp-content/uploads/2021/01/plus.svg"/>
</div>

CSS

#plus {
  -moz-transition: transform 1s;
  -webkit-transition: transform 1s;
  transition: transform 0.3s;
  width: 35px;
  position: fixed;
  top: 20px;
  right: 20px;
}

.rotate {
  transform: rotate(45deg);
}

Basically on the 2nd click, the class is re-adding the class "open", which is causing the menu to flicker as the two actions are conflicting with each other. Video here - https://gph.is/g/ZnNQddo

I have tried adding a delay to the class "open", but for some reason the delay is only working on the first click - on the second it's changing class instantly. This is the code I'm trying for that.

jQuery("#toggle").click(function () {
jQuery('#plus').toggleClass('rotate');
jQuery('#toggle').toggleClass('oxy-modal-close');
  
        var el = jQuery("#toggle");
    window.setTimeout(function() {
        el.toggleClass('open');
    }, 500); 
  
});

Upvotes: 0

Views: 235

Answers (1)

gavgrif
gavgrif

Reputation: 15509

You are referencing the id again within the click - you need to reference $(this)... to toggle the class on the click

Also - you need to start with one of the states - that way it can toggle the class to the other state on each click as per the snippet (the cross icon is on the right of the snippet widow as per styling ) - now when you click it rotates as intended.

$("#toggle").click(function() {
  $('#plus').toggleClass('rotate');
  $(this).toggleClass('open oxy-modal-close');
});
#plus {
  -moz-transition: transform 1s;
  -webkit-transition: transform 1s;
  transition: transform 0.3s;
  width: 35px;
  position: fixed;
  top: 20px;
  right: 20px;
}

.rotate {
  transform: rotate(45deg);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="toggle" class="open">
   <img id="plus" src="http://hausse.co.uk/wp-content/uploads/2021/01/plus.svg"/>
</div>

Upvotes: 1

Related Questions