What is a simple way to hide the menu when the user clicks anywhere on the screen?

I've encountered an issue with my code that involves the following functionalities: 1: When a user clicks a button, it toggles the drop-down menu on or off. 2: Clicking anywhere within the webslides element should close the menu if it's displayed.

The problem arises when the webslides element is positioned beneath the button. I want users to be able to click on the header to also hide the menu, but this function doesn't seem to work as intended. Instead, the button fails to display the menu at all, regardless of how many times I attempt to open it,

var menu = document.getElementsByClassName("dropdown-content")[0];
var header = document.getElementById('header');
var webslidesBody = document.getElementById('webslides');

function lessonSelectionFunction() {
  
  if (menu.style.display === "none") {
    menu.style.display = "block";
  } else {
    menu.style.display = "none";
  }
}

webslidesBody.onclick = function() {
  menu.style.display = "none";
}

header.onclick = function() {
  menu.style.display = "none";
}
<html>

<head>
...

Answer №1

You have integrated a function in both the header and button onclick events to execute "simultaneously". This happens because the button is nested inside the header, causing the style not to change as intended.

Below is the relevant code with a potential solution for your problem:

    var button = document.getElementsByClassName('dropbtn')[0];
    ...
    header.onclick = function(event) {
      if (event.target !== button)
        menu.style.display = "none";
    }

Give it a try:

var menu = document.getElementsByClassName("dropdown-content")[0];
var header = document.getElementById('header');
var webslidesBody = document.getElementById('webslides');
var button = document.getElementsByClassName('dropbtn')[0];

function lessonSelectionFunction() {
  if (menu.style.display === "none") {
    menu.style.display = "block";
  } else {
    menu.style.display = "none";
  }
}

webslidesBody.onclick = function() {
  menu.style.display = "none";
}

header.onclick = function(event) {
  if (event.target !== button)
    menu.style.display = "none";
}
<header id="header">
  <nav role="navigation" class="nav>
    <div class="dropdown">
      <button class="dropbtn" style="text-transform: none;" onclick="lessonSelectionFunction()">Lesson Selection</button>
      <div class="dropdown-content" style="display:none;">
        <a href="#slide=1">Introduction</a>
        <a href="#slide=4">Lesson 1: Methodologies and Development Lifecycle</a>
        <a href="#slide=18">Lesson 2: IT Support</a>
        <a href="#slide=29">Lesson 3: Testing Foundations</a>
        <a href="#slide=42">Lesson 4: Manual Testing Activities</a>
        <a href="#slide=52">Lesson 5: Intro Into Automation</a>
      </div>
    </div>
  </nav>

  <a id="logout" href="logout.php">Logout</a>
</header>

<article id="webslides">

  <!-- First slide -->
  <section class="slideInRight" id="slide=1">
    // REST OF HTML CONTENT ............
  </section>
</article>

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

Stable height with Internet Explorer 6

According to information found on davidwalsh, it is mentioned that in IE6, the container will continue to expand vertically even when a specific height is set. How can I establish a max-height in IE6 so that the container expands with its content until r ...

React - Implementing toggling of a field within a Component Slot

I find myself in a peculiar situation. I am working on a component that contains a slot. Within this slot, there needs to be an input field for a name. Initially, the input field should be disabled until a web request is made within the component. Upon com ...

Model of Objects within a Document

Here's a puzzling question for you: why does console.log(document.body) and console.log(document.head) work perfectly fine, but console.log(document.script) or console.log(document.html) don't seem to do anything? It's strange because all of ...

What is the best method for querying a JSON file using AngularJS?

My Pagination Code: http://plnkr.co/edit/WmC6zjD5srtYHKopLm7m This is a brief overview of my code: var app = angular.module('hCms', []); app.controller('samplecontoller', function ($scope, $http) { $scope.showData = function( ...

Delete the initial double line break and then switch the remaining double line breaks to single line breaks

I am facing an issue with some HTML content fetched from an external source. My aim is to specifically target instances of double br tags using jQuery. I want to delete the first occurrence of double br and convert all subsequent occurrences into single br ...

Changing the color of an image with a click event in HTML

My coding dilemma involves two HTML codes: one displaying a table with grey square buttons, and the other featuring the same table but with orange buttons instead. I am looking for a way to change the color of the button from grey to orange when clicked, ...

Accessing data from charts that have been saved in html format using R highcharter

I utilize the highcharter package in R to visualize data and save the plots as interactive HTMLs. Often, I create multiple graphs and combine them into a canvas for better presentation. require(highcharter) hc_list <- lapply(list(sin,cos,tan,tanh),mapp ...

Unable to save the user's identification in the session

I am in the process of retrieving the user ID of a logged-in user and storing it in the session. This way, when a user submits something, I can include their user ID in the submission to the database. My login page is quite rudimentary, so any guidance wou ...

Swapping out the standard if/else logic for try/catch error

I'm facing a challenge in removing the then statements from this code snippet and replacing all catches with try/catch statements. I'm struggling to figure out how to handle the then statements. export class WelcomePageContribution implements IW ...

Trouble with integrating jQuery Mobile data-role page into a PHP project

Why am I encountering issues when trying to link to the data role page <div data-role="page" id="sessionrecordsuccess"> in the main.php file? Instead of directing me to the specific section, it keeps redirecting to the top of main.php. I have another ...

What is the best way to showcase a ul element as inline-block?

Is there a way to keep the bottom menu aligned in one row on all screen sizes? I attempted using display: inline-block, but it doesn't seem to work for me. Below is the CSS code: footer #middle-footer { background: #F6F6F6; color: #000; font-size ...

Arrange Drifting Components in a Fluid Layout Grid

I am in the process of creating a unique sticky note website where I want to arrange the notes in a grid format. As the window size decreases, the notes should automatically reorganize to fit the width and allow for vertical scrolling. My goal is to achiev ...

Display an icon from the glyphicon library in an Angular application based on a

My Controller: .controller('BlogController', function(blogFactory, $routeParams, $scope){ var that=this; stat=false; this.checkbookmark = function(bId){ console.log(bId) blogFactory.checkBookmark(bId, function(response){ ...

Enhance your Kendo UI File Manager by incorporating image uploading and folder renaming capabilities

Currently utilizing the kendo UI file manager to navigate through my files and images. According to telerik documentation, only the functions to add folders and remove files and folders are supported. However, I am in need of the ability to rename both f ...

Shifting Elements - Navigation triggers subtle movements in CSS styles as you move across pages

I've noticed a strange issue on my website where certain elements seem to be shifting slightly when navigating between different pages. Here's a quick video clip demonstrating the problem. It appears that these elements are not staying static as ...

What's the best way to expand the right side of .li following a left offset of -20px

My nested list structure looks like this... https://i.sstatic.net/sggVx.png What you see is a recursive ul/li setup... <div class="family d-block"> <span class="pb-2"> <small class="text-muted">Family:</small><br> < ...

Enhancing your react-slick carousel with a captivating full-screen background

I need assistance with implementing a full screen slider using react-slick. I am facing difficulty in adding an image as the background. My code snippet looks like this: import image1 from "../assets/bg1.png" import image2 from "../ ...

Is there a way to make the footer adapt to the varying heights of the grid sections as they grow in size?

Currently, I am facing an issue with the positioning of the page footer. Despite my efforts, it does not remain at the bottom as intended. Please refer to the image for a visual representation of the problem. How can this be rectified? It is worth noting ...

The code inside the if statement is somehow executing even when the if statement is not true

Similar Question: Issue with jQuery function running at inappropriate times I've spent several hours trying to figure out why my function isn't working properly. I have a function inside an if ($window.width() < 1000) statement, but it se ...

PHP not receiving values when making an AJAX POST request

My AJAX file below is where I pass all the values from my text boxes and post them to edu.php. In edu.php, I intend to update two tables - details and test. However, nothing seems to be updating in my database. When I checked the values with var_dump, the ...