Hide the off-canvas menu when clicking outside

I recently created a unique "slide-out" menu which you can check out here: SASS Slide-out Menu.
While it is functional, I am looking to add a feature where clicking outside of the menu will automatically close it by removing the "nav-open" class.
I attempted to implement this functionality in the codepen demo, but unfortunately, it did not work as expected:

window.on("click", function(e) {
    if(wrapper.hasClass("nav-open") && e.target != nav && e.target.parent() != nav) {
        wrapper.removeClass("nav-open");
    }
});

Answer №1

You're on the right track! I suggest making a slight adjustment to your codepen example to achieve the desired result:

  $(window).on("click", function(e) {
    if (
      wrapper.hasClass("nav-open") && 
      !$(e.target).parents(nav).hasClass("side-nav") && 
      !$(e.target).hasClass("toggle")
    ) {
        wrapper.removeClass("nav-open");
      }
  });

Here are some helpful pointers for you:

  1. Opt for $(window).on instead of window.on
  2. e.target represents a DOM element, so remember to enclose it in jQuery like $(e.target)
  3. You can compare DOM elements, not jQuery objects, thus utilizing hasClass is necessary
  4. I included a condition to disregard clicks on the toggle itself

Find the revised and functional code on this codepen link: http://codepen.io/anon/pen/mzAru

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

Outputting a variable using javascript

My challenge is to efficiently print the contract variable, which contains HTML content fetched from the server. How can I achieve this easily? I want the print window in Chrome to display the document with the contents of my variable when I click a button ...

I am experiencing difficulties with the state updates, as they are not displaying my products correctly when I select them from

When updating the states setProductsShow and setSelectedCategories, it is important to note that setSelectedCategories is updated before setProductsShow. This sequence is crucial for rendering products correctly. I have come across numerous solutions rega ...

What is the reason behind the decision for Google Chart API to display a legend only for pie charts

I have encountered an issue while attempting to display a pie chart on an ASP.NET webpage using the provided URL: . Despite passing valid values in the URL parameters, only the legend of the chart is displayed and not the chart itself. Can anyone provide i ...

How should dates be formatted correctly on spreadsheets?

Recently, I have been delving into Google Sheets formats. My approach involves utilizing fetch and tokens for writing data. rows: [{ values: [ { userEnteredValue: { numberValue: Math.round(new Date().getTime() / 1000) }, userEnteredFormat: { ...

Creating mathematical formulas in JavaScript

How can the equation be translated into JavaScript? This is the proposed programming solution, but there seems to be an issue. var MIR = parseFloat(($('#aprrate').val() / 100) / 12); var paymentAmount = (MIR * $('#amounttofinance').va ...

Trouble arises when incorporating a new feature onto a map with OpenLayers and Vue.js

I'm currently working on integrating a custom control into my map using OpenLayers with Vue.js. The Explore.vue component is responsible for creating the "map" (olmap) with OL, and I bind it to the child component LeftSideBar2.vue. However, when att ...

What is the best way to align a form within a navigation bar?

I am working on a Bootstrap4 Navigation bar with a brand and some links (nav-item). However, I am facing a challenge with centering a search form inside the nav bar. I want the form to be completely centered within the entire navbar, rather than taking up ...

Is there a maximum size restriction for submitting forms using jQuery's AJAX method?

I am searching for a way to submit a form without having to load a new PHP page. The form I need to submit contains both file upload and textarea fields, which means it may contain large data that needs to be submitted. While looking through various tutor ...

Tips for adding animation to the div instead of the content

I have implemented a hover animation to animate the div, but unfortunately, when I added the animation to #i :hover {}, it ended up animating the words only. Moreover, the cursor transforms into a pointer solely when hovering over the words instead of the ...

Is it possible to nest components within one another in Angular?

It seems similar to this: <app-component1> <app-component2></app-component2> </app-component1> I couldn't locate any information about this in the Angular documentation. Whenever I try to use a component within another com ...

What's the Deal with Blank Square Brackets in JavaScript?

While browsing through , I stumbled upon this code snippet: useEffect(() => { const interval = setInterval(() => { console.log('This will run every second!'); }, 1000); return () => clearInterval(interval); }, []); I am intri ...

Separate .env configurations tailored for development and production environments

Managing different content in my .env files is crucial as I work with both next.js and node.js. The settings vary between development and deployment environments. During development: DOMAIN_URL=https://localhost:3000 GOOGLE_CLIENT_ID='abc' For ...

Using Node.js Puppeteer to interact with dynamically generated elements

Currently, I'm utilizing puppeteer for node.js version 13.3.1 to develop a bot that will automate job applications on LinkedIn. The code I have so far is as follows: const puppeteer = require('puppeteer'); const SEARCHPARAM = "react& ...

Empty response received from AJAX .post request to PHP backend

I'm having trouble with creating a system to check the availability of usernames. I'm not receiving any response back and even though there are no errors in the console, all I get is a 200 OK status without any response, which should be stored in ...

Contrasting the disparities between creating a new RegExp object using the RegExp constructor function and testing a regular

Trying to create a robust password rule for JavaScript using regex led to some unexpected results. Initially, the following approach worked well: const value = 'TTest90()'; const firstApproach = /^(?=(.*[a-z]){3,})(?=(.*[A-Z]){2,})(?=(.*[0-9]){2 ...

Tips for isolating data on the current page:

Currently, I am using the igx-grid component. When retrieving all data in one call and filtering while on the 3rd page, it seems to search through the entire dataset and then automatically goes back to "Page 1". Is there a way to filter data only within th ...

necessity for a condition in Material UI input field

I need assistance with a function that I use to incorporate Material UI text fields into my code. The issue I'm currently facing is figuring out how to dynamically add the "required" attribute based on a boolean parameter that determines whether the f ...

Searching for image labels and substituting the path string

Upon each page load, I am faced with the task of implementing a script that scans through the entire page to identify all image src file paths (<img src="/RayRay/thisisianimage.png">) and then add a specific string onto the file paths so they appear ...

Unraveling exceptions in Node.js akin to handling them in Java

I'm seeking to develop a node application and I need guidance on exception handling. In Java, we utilize the exception class for this purpose. How can I achieve something similar in node? Are there any libraries available specifically for handling exc ...

What is the best way to customize the border color of a disabled Material UI TextField?

I'm struggling to override the default style for disabled Mui TextField components, particularly in changing the border color. Although I successfully altered the label color for disabled fields, I can't seem to get the border color to change. T ...