jqueryclickconflict

jQuery conflict between click and touchstart/touchend


I have a section that detects the touchstart and touchend (it works), but I have a link that doesn't detect the click.

What's happening?

#main uses overflow. Is that the problem?

$("#main").on("touchstart, touchend", function(e) {
  e.preventDefault();

  console.log("touch zone>");
})

$(document).on("click", "#main a", function(e) {
  e.preventDefault();

  console.log("Button click");
});
#main {
  width: 40vh;
  height: 90vh;
  overflow: hidden auto;
  background: Gray;
}
<section id="main">
  <h1>Title demo <a href="#">Link</a></h1>
  <p>Lorem Lorem Lorem Lorem Lorem Lorem</p>

  <h1>Title demo <a href="#">Link</a></h1>
  <p>Lorem Lorem Lorem Lorem Lorem Lorem</p>

  <h1>Title demo <a href="#">Link</a></h1>
  <p>Lorem Lorem Lorem Lorem Lorem Lorem</p>

  <h1>Title demo <a href="#">Link</a></h1>
  <p>Lorem Lorem Lorem Lorem Lorem Lorem</p>

  <h1>Title demo <a href="#">Link</a></h1>
  <p>Lorem Lorem Lorem Lorem Lorem Lorem</p>

  <h1>Title demo <a href="#">Link</a></h1>
  <p>Lorem Lorem Lorem Lorem Lorem Lorem</p>
</section>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>


Solution

  • Anchors are for navigation and buttons are for actions. Be sure you're using the correct element for the task. You may style them as desired.

    That may help also by eliminating the need for preventDefault(), which I believe is the problem.

    Other tips:

    $("#main").on("touchstart, touchend", () => {
      console.log("touch zone");
    })
    
    $(document).on("click", "#main button", () => {
      console.log("Button click");
    });
    .main {
      width: 40vh;
      height: 90vh;
      overflow: hidden auto;
      background: Gray;
    }
    <section id="main" class="main">
      <h1>Title demo <button>Action</button></h1>
      <p>Lorem Lorem Lorem Lorem Lorem Lorem</p>
      <h1>Title demo <button>Action</button></h1>
      <p>Lorem Lorem Lorem Lorem Lorem Lorem</p>
      <h1>Title demo <button>Action</button></h1>
      <p>Lorem Lorem Lorem Lorem Lorem Lorem</p>
      <h1>Title demo <button>Action</button></h1>
      <p>Lorem Lorem Lorem Lorem Lorem Lorem</p>
      <h1>Title demo <button>Action</button></h1>
      <p>Lorem Lorem Lorem Lorem Lorem Lorem</p>
    </section>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>