plain javascript, onclick not working on mobile

后端 未结 3 1234
失恋的感觉
失恋的感觉 2021-01-24 03:47

Now I am not a star really with Javascript, but i seem to encounter the all known problem with mobile devices and the onclick function. Onclick requires a mouse action where off

相关标签:
3条回答
  • 2021-01-24 04:13

    Binding the click event listener to the element should fix the problem you've been having.

    btn.addEventListener("click", function() {
        var x = window.innerWidth;
        if (x > 768) {
            //event.preventDefault();
            modal.style.display = "block";
        } else {
            //event.preventDefault();
        }
    });
    

    Alternatively, you could try using the touchstart event, which works just like the "mousedown" event, just for mobile.

    elem.addEventListener("touchstart", handler);
    

    Your code would look like this:

    btn.addEventListener("touchstart", function() {
        var x = window.innerWidth;
        if (x > 768) {
            //event.preventDefault();
            modal.style.display = "block";
        } else {
            //event.preventDefault();
        }
    });
    
    0 讨论(0)
  • 2021-01-24 04:14

    Try to change onclick to addEventListener and see if that helps you..

    // When the user clicks the button, open the modal 
    btn.addEventListener('click', function () {
        var x = window.innerWidth;
        if (x > 768) {
            //event.preventDefault();
            modal.style.display = "block";
        } else {
            //event.preventDefault();
        }
    });

    You can also pass named function to addEventListener

    0 讨论(0)
  • 2021-01-24 04:37

    Had the same issue, after setting z-index to 100 it worked. Seems like in my case there was a z-index issue.

    0 讨论(0)
提交回复
热议问题