Mohamed Atef
Mohamed Atef

Reputation: 23

window.addEventListener code is not working on mobile

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

Upvotes: 1

Views: 4966

Answers (1)

James_F
James_F

Reputation: 449

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) { ... }

Upvotes: 1

Related Questions