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>

1
  • 1
    Why have you used a submit button in a form in the first place for this? Commented Jul 2, 2020 at 17:39

1 Answer 1

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.