skip to Main Content

I’ve searched a lot about this issue, however is slightly different from the others. Most of posts here relates to "toggle not working", but mine toggle works, the problem is that it doesn’t change the view, it doesn’t open/close element.

Check the snippet below, you’ll see that does work on desktop but does not in mobile view.

Is there any special JS rule to make it works in mobile browsers or something related to touch screens? How to make it work?

  function toggleForm(event) {
    console.log("clicked");

    var form = document.getElementById('search-form');
    form.classList.toggle('hidden-form');

    console.log(form.classList);
  }
.hidden-form {
    display: none !important;
    height: auto !important;
}
<div onclick="toggleForm()" id="toggleButton">
  <h3>TITLE</h3>
</div>

<form action="#" id="search-form" class="hidden-form">
  TEXT
</form>

2

Answers


  1. It depends on the device you’re using. Try adding touchstart event listener for mobile

    In your case:

    <div ontouchstart="toggleForm()" id="toggleButton">
      <h3>TITLE</h3>
    </div>
    

    *The most efficient way is to have an if statement in your script and add touchstart or click event listener based on the users device (desktop or mobile)

    Login or Signup to reply.
  2. You can do change in your code like this –

    Ensure your HTML document includes the viewport meta tag in the section

    <meta name="viewport" content="width=device-width, initial-scale=1">
    
    document.addEventListener('DOMContentLoaded', function() {
      var toggleButton = document.getElementById('toggleButton');
      var toggleForm = function() {
      console.log("toggled");
      var form = document.getElementById('search-form');
      form.classList.toggle('hidden-form');
      console.log(form.classList);
      };
      toggleButton.addEventListener('click', toggleForm);
      toggleButton.addEventListener('touchstart', toggleForm);
    });
    .hidden-form {
      display: none !important;
      height: auto !important;
    }
    <div id="toggleButton">
        <h3>TITLE</h3>
    </div>
    <form action="#" id="search-form" class="hidden-form">
        TEXT
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search