window.addEventListener code is not working on mobile

28
February 02, 2019, at 1:40 PM

Please i have issue in my JS code i built this code because i'd like when the visitor click on another div (not the menu )the menu will close if it open this is the code but this code don't work on mobile phones but it work in developer tools on chrome or firefox

<script>
window.addEventListener('mouseup', function(event){
    var box = document.getElementById('narvbar_menu');
    if (event.target != box && event.target.parentNode != box){
        box.style.display="none";
        document.getElementById("close_menu").style.display="none";
    }
});
</script>

Best regards

Answer 1

This is because "mouseup" doesn't fire on mobile devices. Just also listen for "touchend":

EDIT: The below code should append event listeners for both "mouseup" and "touchend" to window.

<script>
    ["mouseup", "touchend"].forEach(function(e) {
        window.addEventListener(e, function(event){
            var box = document.getElementById('narvbar_menu');
            if (event.target != box && event.target.parentNode != box){
                box.style.display="none";
                document.getElementById("close_menu").style.display="none";
            }
        });
    })
</script>

If you don't want to listen for multiple events, "click" should work for both mobile and desktop:

window.addEventListener("click", function(event) { ... }
READ ALSO
Updating Data to gauges Needle

Updating Data to gauges Needle

Thank you for your timeI can't get the Needle on the Gauge to move I used the following and no luck

56
Why is array.push() not working correctly?

Why is array.push() not working correctly?

I have a function which returns an array of dishes from a firestore databaseWith console

28
How to prevent non-breaking spaces from being created in a contenteditable element?

How to prevent non-breaking spaces from being created in a contenteditable element?

I have a contenteditable div, which creates many non-breaking spaces when words are deleted or addedThis is the format of my code:

41