The window.addEventListener function is failing to work properly on mobile devices

Hey there! I am facing an issue in my JS code. I wrote this code because I want the menu to close when a visitor clicks on another div (not the menu) if it is open. The code seems to be working fine in developer tools on Chrome or Firefox, but it's not working on mobile phones.

<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>

Thanks for your help!

Answer №1

This is due to the fact that the event "mouseup" does not trigger on mobile devices. To address this, also include an event listener for "touchend":

UPDATE: The code below will add event listeners for both "mouseup" and "touchend" to the 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 prefer not to listen for multiple events, using "click" should suffice for both mobile and desktop users:

window.addEventListener("click", function(event) { ... }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leverage Vue's ability to inject content from one component to another is a

I am currently customizing my admin dashboard (Core-UI) to suit my specific needs. Within this customization, I have an "aside" component where I aim to load MonitorAside.vue whenever the page switches to the Monitor section (done using vue-router). Here ...

Using CSS properties as false values within React applications

Can you provide guidance on using conditional styles with conditional operators? What would be the ideal code example? Is it possible to use non-CSS values? margin: isOpen ? '10px' : undefined margin: isOpen ? '10px' : 'initial&a ...

Is it possible to minify HTML in PHP without parsing JavaScript and CSS code?

After finding a solution in this discussion, I successfully managed to 'minify' HTML content. function process_content($buffer) { $search = array( '/\>[^\S ]+/s', // eliminate spaces after tags, except for ...

Unlocking the potential: passing designated text values with Javascript

In my current React code, I am retrieving the value from cookies like this: initialTrafficSource: Cookies.get("initialTrafficSource") || null, Mapping for API const body = {Source: formValue.initialTrafficSource} Desired Output: utmcsr=(direct)|utmcmd=(n ...

Encountering a "Connection Refused" error when attempting to test a React and Express application

Currently, I am developing an order system using React for the frontend (port 3000) and Express for the backend (port 3001). Everything functions perfectly when tested on the same MacBook that hosts the node project. However, when testing it on a differen ...

Interacting with a WCF service using jQuery

Recently, I have been attempting to utilize a JSON file to consume a WCF service. My goal is to extract values from a basic HTML form and then pass those values into an object instantiated in the WCF using JSON. Despite my best efforts, I have not been suc ...

What is the process for transferring information from a Microsoft Teams personal tab to a Microsoft Teams bot?

Is it feasible to share data such as strings or JSON objects from custom tab browsers to a Teams bot's conversation without utilizing the Graph API by leveraging any SDK functionality? ...

Tips for extracting JSON data from an API with identical names as values

I am working on a project to create a data search system using JSON. The JSON data is stored in a REST API, and the structure of the API is as follows: [ { "info": "cute but big animal", "type": "pig", ...

Passing a Javascript variable to the NAME attribute of an HTML <a href> tag: Steps to do it efficiently

I need assistance with passing a JavaScript variable to the NAME attribute of an HTML tag. Let's consider this script example: <script> var name = "Click here!"; </script> My goal is to pass the variable to some code in order for <a ...

AngularJS: Modifying directive according to service value update

In my current application, I have a basic sidebar that displays a list of names fetched from a JSON call to the server. When a user clicks on a name in the sidebar, it updates the 'nameService' with the selected name. Once the 'nameService& ...

javascript authorization for iframes

I am currently working on a localhost webpage (parent) that includes an iframe displaying content from another url (child; part of a different webapp also on localhost). My goal is to use JavaScript on the parent-page to inspect the contents of the iframe ...

Issue with PHP form not saving data and correctly parsing output

I am facing an issue with my PHP page where it is supposed to grab responses from a form, insert the data into a table, and then display the response on the same page. I am using ajax to send form values without refreshing the page, but unfortunately, no i ...

Align the subtext to the right and center it vertically within a Bootstrap dropdown menu item

Is there a way to vertically align small captions on the right side of a dropdown menu, next to each item's text? The issue is that in the example below, the numbers are not properly aligned. https://i.stack.imgur.com/NZigW.png The numbers 123 and 1 ...

The Slack Bot is having trouble downloading files from direct messages, but it is successfully downloading them when uploaded to a channel

I have developed a program to retrieve files using a code snippet provided by a Slack bot. Below is the code: var https = require('https'); var fs = require('fs'); var downloadFile = function (url, dest){ var slug = url.split(&apos ...

Element with absolute positioning inside a relative parent does not interfere with other elements outside of the parent

I am currently facing a challenge with a simple dialog that is positioned absolutely in the center of the screen. Inside this dialog, there is a dropdown with a relatively positioned parent (I want the dropdown to follow its parent's position without ...

JavaScript - I have a variable trapped inside a function and I'm struggling to retrieve it

Is it possible that I'm missing something obvious here? I am really struggling to pass the 'body' variable out of this nested function. function retrieveFacebookInfo(userID) { request({ "url": "https://graph.facebook.com/v2.6/" + ...

Creating a concise TypeScript declaration file for an established JavaScript library

I'm interested in utilizing the neat-csv library, however, I have encountered an issue with it not having a typescript definition file available. Various blogs suggest creating a basic definition file as a starting point: declare var neatCsv: any; M ...

Looking for a solution to eliminate Parsing Error: Unexpected Token when developing with React? I've already implemented ESLint and Prettier

Currently, I am working on building a form in React with MUI. Below is the code snippet that I have been working with: const textFields = [ { label: 'Name', placeholder: 'Enter a company name', }, { label: 'Addres ...

Pair objects that possess a specific attribute

I have a HTML snippet that I want to modify by adding the CSS class HideEdit to hide specific columns. <th class="rgHeader" style="text-align: left;" scope="col" _events="[object Object]" control="[object Object]" UniqueName="Edit"> This particular ...

The addition and deletion of classes can sometimes lead to disruptions in the DOM

I've been struggling to phrase this question for a while now. I'm working on a single-page e-commerce site that operates by modifying the HTML in divs and using CSS along with JQuery to show and hide those divs. My problem arises when, occasional ...