Simply close by clicking outside using basic vanilla JavaScript

I have successfully implemented a menu that closes (removes the added class) when clicking outside the menu button area.

Although it is working fine, I am unsure if my code is correct. My understanding is that the click outside functionality should only be triggered when the .newClass is added to the div. How can I make this adjustment? I am relatively new to JavaScript.

var b = document.getElementById("menu");
document.addEventListener("mouseup", function(event) {
  var clickOnMenu = b.contains(event.target);
  if (clickOnMenu) {
    b.classList.toggle("newClass");
  } else {
    b.classList.remove("newClass");
  }
});
div.box {
  margin: auto;
  padding: 1em;
  max-width: 6em;
  background: rgba(0, 0, 0, 0.6);
  text-align: center;
  color: white;
  transition: .2s ease-in-out;
  cursor: pointer;
}

div.box:hover {
  background: rgba(0, 0, 0, 0.7);
}

div.newClass {
  padding-bottom: 100px;
}
<div id="menu" class="box">Menu</div>

Answer №1

Hopefully this information is beneficial to you

var element = document.getElementById("menu");
document.addEventListener("mouseup", function(event) {
  var targetId = event.target.id;
  if(targetId == "menu" ) {
    element.classList.add("newClass");
  } else {
    element.classList.remove("newClass");
  }
});
div.box {
  margin: auto;
  padding: 1em;
  max-width: 6em;
  background: rgba(0, 0, 0, 0.6);
  text-align: center;
  color: white;
  transition: .2s ease-in-out;
  cursor: pointer;
}

div.box:hover {
  background: rgba(0, 0, 0, 0.7);
}

div.newClass {
  padding-bottom: 100px;
}
<div id="menu" class="box">Menu</div>

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

Fill every empty element with elements from another array

I'm struggling to grasp the concept of arrays. I have two arrays and I want to replace the null elements in one with the elements from the other. Here is what I have currently: var arr1 = [1,2,3,4] var arr2 = [null, 99, null, null] arr2.map((item) = ...

Unable to retrieve this object because of a intricate JavaScript function in Vue.js

For my VueJs project, I am utilizing the popular vue-select component. I wanted to customize a keyDownEvent and consulted the documentation for guidance. However, I found the example provided using a mix of modern JS techniques to be quite cryptic. <tem ...

Instructions for ordering this jQuery script that executes ajax and should return a 'true' value

In my javascript for form validation, I have added a new layer that calls an external function to send an Ajax request with the form validation results. The goal is to receive an email indicating whether the user passed or failed the validation. While cal ...

The communication between the Next.js and Node.js servers is being obstructed as the request body fails

Could you lend me a hand with this issue? Here is the function being called: function apiCreate(url, product) { console.log('Posting request API...' + JSON.stringify(product) ); fetch(url, { dataType: 'json', method: 'post ...

Creating dynamic button names and detecting the pressed button in PHP

Right now, I am experimenting with PHP to create a unique project. This experiment is just a small part of a larger file that I am working on. Essentially, the aim is for the program to generate a series of submit buttons within a form, each assigned a dis ...

One of the functionalities is not functioning properly: either the validation or the AJAX

My validation code was working fine until I added some ajax code. Now, when I include the onclick="return chk()" in the submit input field, the validation code stops working. But if I remove it, the ajax code doesn't work. How can I resolve this issue ...

Guide to applying Bootstrap styles to a specific section of an HTML document

What can I do to ensure that the Bootstrap library used by the main app does not affect the styling of my controls when integrating my web application inside the main app? I want to maintain the current styles of my controls without any interference from ...

Ways to assign a CSS class specifically for images

.calendarList { background-image: url('/resource3/hpsc/common/images/calendar.png'); background-position: 135px 50%; background-repeat: no-repeat; cursor:pointer; } <input type="text" id="toDatepicker" class="cal ...

Disordered block elements

I am having trouble centering a div in my footer. When I try to center it, the div ends up floating on top of the footer instead. Here is the link to the codepen. footer { text-align: center; background-color: grey; position: fixed; bottom: 0; width: 100 ...

``Sorry, the link redirection feature is currently experiencing technical

First and foremost, take a look at this example View here Based on the example provided, I would like to create a similar page using the Telrik Text Editor, with a list of links and their corresponding paragraphs. Here is the HTML I am using in the Telr ...

Tips for transforming intricate JavaScript arrays into a unified array and iterating through to create a table

I need help combining two arrays that contain objects and reassigning the values in a standard format. Can anyone provide some guidance? Thank you. Here is my current situation: array1 = [{Apple: Ken, Orange: Mary, Melon: Tina, Strawberry: Jessica, Mango ...

React - onchange event for input checkboxes does not trigger on the initial click

The behavior of a checkbox input is proving to be quite unreliable. Currently, I am setting the checkbox state based on the store's state, which generally works well. However, there are instances where checking the checkbox does not trigger the oncha ...

Enhance User Experience with ngDialog Modal's Multi-pane Feature for Angular

Looking at the ngDialog example, they showcase a modal with multiple 'panes' that can be scrolled through: . After going through the ngDialog guide, I couldn't find a straightforward way to achieve this. Any suggestions on how to add a butt ...

Is it possible for an HTML number input's arrows to change in increments that are different from its designated step attribute?

Within my design, I have implemented an <input type="number" step="1"> element for selecting font size. However, in the context of working on a large canvas, adjusting the number by 1 is hardly noticeable. It would greatly enhance ...

Enclose a pair of divs within a fresh div wrapper for better organization

Imagine you have the following: <div class="somediv"></div> <div class="somediv"></div> <div class="somediv"></div> <div class="somediv"></div> <div class="somediv"></div> <div class="somediv" ...

Steps for making a button with both an image and text:

I am in the process of designing a basketball-themed website and I am looking to incorporate custom icons/buttons that link to various pages on the site. My vision is to have a unique button that features a circular image with accompanying text below it. ...

Enhancing Communication Between JavaScript and PHP

Positioned within my form is an input field where users can enter their postcode. The shipping cost for their order will be determined based on this postcode, utilizing PHP to assign different costs depending on the zone. After the user enters their postc ...

Having trouble integrating MaterialUI Datepicker, Dayjs, useFormik, and Yup

Currently, I am facing a recurring issue with the Material UI Date picker in conjunction with day js. The problem arises when I select a date on the calendar for the first time, it updates correctly in the text field but fails to work thereafter. Additiona ...

Looking to implement pagination in Vue.js - what steps should I take?

Hi there, I'm currently facing an issue while trying to paginate my data. The error message in my console reads: Property or method "$index" is not defined on the instance but referenced during render. Below is my HTML template where I display the da ...

Exploring the Integration of Callbacks and Promises in Express.js

I'm currently developing an Express.js application where I am utilizing x-ray as a scraping tool to extract information. For each individual website I scrape, I intend to establish a unique model due to the distinct data and procedures involved in th ...