plain javascript, onclick not working on mobile

2020-05-07 04:18发布

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 course on the phone that doesnt apply. Now in Jquery, you can use "on" .. but how does this work with regular javascript?

// Get the modal
var modal = document.getElementById('reserveer-modal');

// Get the button that opens the modal
var btn = document.getElementById("reserveer-knop");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal 
btn.onclick = function() {
    var x = window.innerWidth;
    if (x > 768) {

        //event.preventDefault();
        modal.style.display = "block";
    } else {
        //event.preventDefault();
    }
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}

标签: javascript
3条回答
老娘就宠你
2楼-- · 2020-05-07 05:05

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();
    }
});
查看更多
beautiful°
3楼-- · 2020-05-07 05:08

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

查看更多
家丑人穷心不美
4楼-- · 2020-05-07 05:12

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

查看更多
登录 后发表回答