0

I've included a much-simplified example of the situation I'm running into.

I have an ajax mini-cart that is a form that slides out. I have a "close cart" button that is just supposed it hide the cart, but the on.("click", does not fire correctly because it's wrapped within a form element. I cannot take the close button out of the form because of how this is built.

$("#open-slider").on ("click", () => {
  $("#slider").css("opacity","1");
});

$("#close-slider").on ("click", () => {
  $("#slider").css("opacity","0");
});
.header {
  width:100vw;
  height:60px;
  background-color:red;
}

#slider {
  height:100px;
  width:100px;
  background-color:blue;
  opacity: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="header">  
  <button id="open-slider">
    Open slider
  </button>
  <form id="slider">
    <div class="slider-header">
      <button id="close-slider"> close </button>
    </div>
  </form>
</div>
Robolisk
  • 1,682
  • 5
  • 22
  • 49

1 Answers1

1

It's because the form is being submitted. You have to prevent that event like this:

$("#close-slider").on("click", e => {
  $("#slider").css("opacity","0");
  e.preventDefault();
});

Example fiddle.

Please note, that setting opacity of element is not a good approach in that case. It's still there, just invisible. You can still click on the element when it has opacity of 0. Check on your (not modified) example, that you can click close button before clicking the open slider button. You should use display:none to hide it instead.

Flash Thunder
  • 11,672
  • 8
  • 47
  • 91