Tips for closing a dropdown menu on mobile screens when a user taps outside of it

I am encountering a difficult issue with this HTML template Click Here. To resolve it, please navigate to the 1st template Demo under Shop Pages as indicated in the image below.

https://i.sstatic.net/TlutO.jpg

(Please adjust your browser to a mobile screen size)

Currently, when a user opens the mobile dropdown menu on the left, they should be able to close it by clicking outside the menu, anywhere else on the page. The current behavior only allows closure by clicking the hamburger icon.

In addition, if the user has the menu open and clicks on the page but then attempts to click the hamburger icon again due to the initial click not working, the page freezes and requires multiple taps to scroll again, causing inconvenience for mobile users.

I have tried to address this issue with the code snippet below. However, once the menu slides back up, it does not reappear:

<script>
$(document).on("click", function (event) {
    var $trigger = $(".mobile-menu.hamburger-icon");
    if ($trigger !== event.target && !$trigger.has(event.target).length){           
        //THIS IS WHAT WORKS BUT YOU HAVE TO CLICK OUTSIDE LIKE TWICE FOR IT TO COME BACK
        $(".mobile-navigation.dl-menuwrapper").slideUp("fast");                                                     
    }               
});
</script>

I also attempted adding another piece of code to allow the menu to appear again when the user clicks the hamburger icon, but it caused buggy behavior as the menu would slide down once and disappear upon further interaction:

<script>
$(document).on("click", function (event) {
    var $trigger = $(".mobile-menu.hamburger-icon");
    if ($trigger !== event.target && !$trigger.has(event.target).length){           
        //THIS IS WHAT WORKS BUT YOU HAVE TO CLICK OUTSIDE LIKE TWICE FOR IT TO COME BACK
        $(".mobile-navigation.dl-menuwrapper").slideUp("fast");                                                       
    }               
});
</script>

<script>
    $(".mobile-menu.hamburger-icon").on("click", function (event) {        
        $(".mobile-navigation.dl-menuwrapper").slideDown("fast");                            
    });
</script>

How can I ensure this functionality works correctly as needed? Thank you!

Answer №1

To improve the functionality, I made some modifications by introducing custom classes to the div for the icon button. Additionally, I incorporated the following code snippet which appears to have resolved the issue effectively.

<script>
$(document).on("click", function (event) {
    var $BMI = $(".mobile-menu.hamburger-icon");
    var $VMM = $(".dl-menu.dl-menuopen");
    
    if ($BMI !== event.target && !$BMI.has(event.target).length && ($VMM.is(":hidden"))) {
                              
        $(".mobile-navigation.dl-menuwrapper.open-mobile-menu").addClass('open-mobile-menu');
        
        $(".dl-menu.dl-menuopen").addClass('dl-menuopen');           
    }        
    
 </script>

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

Transferring information from a partial view to the main view

I need help passing a value from a partial view to the parent view. I attempted the solution below, but it didn't work for me. Could someone assist me with how to achieve this? My goal is to hide a button in the parent view based on the value returned ...

Is it possible for the background color to change in a sequence every time the page

I'm having trouble figuring out how to create a sequence that changes the background color every time the page is refreshed. I'm comfortable with basic HTML but not so much with JavaScript or CSS. I'm working on a page where I want the backg ...

Achieving Navbar overlap on Carousel with Bootstrap

Is there a way to make the bootstrap navbar overlap with the carousel without causing any issues with #test? HTML <nav class="navbar navbar-expand-lg navbar-dark bg-dark floating-navbar"> <div class="container"> & ...

What is the process for sending a complicated object to an MVC 4 controller using Ajax?

I am working with two objects in my project. The first one is DrawDie which has properties like ID, PlantID, QtyOnHand, SizeUS, SizeMetric, CaseSize, and Style. The second object is called DieOrder, which has properties such as ID, DrawDie (reference to a ...

The QR code disappears from the screen once the button is no longer pressed

After following an online tutorial on creating a QR code generator, the code works fine and I am able to display the image. However, I'm facing an issue where the image disappears from the screen once the button is released. Here is the code snippet: ...

Utilizing regular expressions to find the attribute name within nested array brackets by matching the index number

Can someone assist me with RegEx? I am trying to extract only the index number found within brackets [1] in a string that looks like this: text[alphanumeric][index][text]. Please see the example attribute name below. name="lorem[ipsum_dolor_set-amet-34][1 ...

What is the best way to effectively test jQuery's .ajax() promises using Jasmine and/or Sinon?

There is a simple function that returns a jQuery .ajax() promise: CLAW.controls.validateLocation = function(val, $inputEl) { return $.ajax({ url: locationServiceUrl + 'ValidateLocation/', data: { 'locationNam ...

Storing persistent JSON data in a mobile app built with HTML5 involves utilizing the local storage capabilities of the

I am currently working on a mobile app using PhoneGap that is based on HTML technology. When the app is opened for the first time, my goal is to have it download a zip file that includes a JSON file and media files such as images or audio. Once the zip f ...

Utilizing conditional statements for confirming purchased orders with a pop-up confirmation box

function purchaseClicked() { var orders = prompt("Are you sure you want to buy these Items?"); if (orders != null) { alert('Please try selecting your items again!') } else { alert('Thank you for shopping ...

Adjust the size of the embedded iframe to match the dimensions of the containing div

Is there a method to resize the iframe embed code for a vine so that it fits within the boundaries of the enclosing div? The supplied embed code already includes sizing information as shown below: <iframe src="https://vine.co/v/iMJzrThFhDL/embed/simp ...

Retrieve the value of a related object based on the user's click

Check out this sample code on JSFiddle <a href="#"></a> <a href="#"></a> <a href="#"></a> <a href="#"></a> <div></div> JavaScript: function Product(name, price){ this.name = name; this. ...

How can ASP.Net render "partial" pages without including the <html> tags and similar elements?

In my ASP.Net Webforms project, I am attempting to incorporate jQueryUI AJAX tabs. However, I have encountered a roadblock. When using AJAX, it is necessary to render only a partial page (without <html> and similar elements) through an external URL. ...

Tips for concealing the edges of a scroll bar while utilizing scroll as overflow

Basically, I have a div that is positioned absolutely and has multiple children elements. This div can be scrolled horizontally to see all its content, but the scrollbar hangs off the bottom, hiding the bottom border radius. Here is the HTML code: <ul ...

Tips on personalizing the checkbox by incorporating a custom background image

Looking to spruce up the standard checkbox? We're open to any method - whether it's a background image, CSS3, or some jQuery magic. Check out this example for inspiration! ...

Navigational bar customization: Troubleshooting search button functionality

I've been encountering some challenges with the search form in bootstrap 4.1's navbar. I've been referring to this documentation link for assistance. The search form I have set up appears quite typical for bootstrap: https://i.sstatic.net/I ...

Ajax not functioning after submission of form

I currently have this code snippet: $('#my_form').submit(function () { setTimeout(function () { console.log('1'); $.ajax({ type: "GET", url: "/CorrectUrl/CorrectUrl", ...

The validations in Ajax submission fail to trigger any action following a successful response

My form validation script is not working properly. After correcting all errors and warnings, the submit button does not respond. It's not inserting any data into the database when clicked. Additionally, I have styled input validations in individual d ...

AngularJS - ng-repeat not updating when property array changes

I have a loop in my HTML using ng-repeat: <div class="row"> <div ng-repeat="item in model.painel track by item.codigoIncidente"> <strong>{{item.restante.horaMinutoSegundo}}</strong> </div> </div> In ...

Sending a JavaScript variable to PHP and retrieving the PHP result back into a JavaScript variable

I am looking to transfer a JavaScript variable to a PHP file using AJAX, and then retrieve the PHP file's output back into a JavaScript variable. For sending the JavaScript variable to the PHP file, I found a method that suggests using ajax to assign ...

What is the best way to position four circles within a square container using CSS?

<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> .circles { height: 150px; width: 150px; background-color: #bbb; border-radius: 50%; displ ...