Click anywhere on the body to conceal this element

I am currently working on a website where I have implemented a hidden menu that is functioning correctly. However, I want to make it so that when the menu is visible, users can click anywhere on the body to hide it.

Unfortunately, my current code is not working properly and I am getting an error message "Attempting to assign readonly property" while using codeine. This error also causes the entire page to disappear.

In addition to this issue, I am utilizing parallax.js and fullPage.js in this website's design. Below is the segment of code related to this problem:

//function hideMenu {
    //var $menu_visivel = $('.menu2').is(":visible");

    //if ($menu_visivel) {

      //$('body').click(function() {

      //});

    //} else {

    //};
//}

You can view the full Pen and the debug page for further details. Thank you in advance for your help.

Answer №1

Discover a live demonstration in CODEPEN.

You can implement a click event on the document to conceal the element. Furthermore, you must incorporate a stopPropagation event for the element:

$(document).click(function(event) {
    //inspect for clicks outside of .menu and .menuButton
    if(!$(event.target).closest('.menu, .menuButton').length && !$(event.target).is('.menu, .menuButton')) {
         // verify if .menu is currently displayed
         if($('.menu').css("left") == "0px") {
            $(".menu").animate({
                left: "-200px"
            },200);
         }
    }       
});

To display on .menuButton and hide upon loading:

$(".menu").animate({
   left: "-200px"
},200);

$(".menuButton").click(function() {
   // easy to enhance it for hiding as well
   $(".menu").animate({
     left: "0"
   },200);
});

This instance clearly indicates that the parallax plugin is causing issues with your code.

Additionally, you have an extra $(document).ready() inside the outermost one. It should be removed. Moreover, the functionality presently only works when right-clicking once on the page. Left-click doesn't function correctly. According to my observation and this informative post HERE, this could be due to the plugin since the vertical scrollbar on your <p> tag does not appear unless you right-click on the page.

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

HTML5 Positioning Timeout

While working on my project, I incorporated the HTML Geolocation feature. However, I have observed that it is not always dependable. I am looking for a solution to add a backup plan that will time out after x seconds and display an error message. Any sugg ...

If the index is greater than 0, then continue looping; otherwise, execute only once using JSON and jQuery

After customizing a jQuery paging script that I found on Paging Through Records Using jQuery, the paging functionality is working well. It can handle different javascript responses effectively. However, there is one issue. The response expects the JSON to ...

Is the "cache" parameter in jquery AJAX suitable for my requirements?

At the moment, I am utilizing a function that refreshes the entire #comments div only. $.ajax({ url: 'WebForm1.aspx', success: function (data) { $("WebForm1.aspx #comments").html(data); } }); I am exploring the possibility of using ...

How to ensure scrollbar adjusts to increasing height when using scroll:auto?

My <div> element has the style property scroll:auto. Whenever text is added to the <div> and the content height exceeds the default height, I find myself having to scroll down in order to see the latest lines of text that have been added. What ...

Implementing a jQuery method in a PHP page that is loaded through AJAX

I am facing an issue on my page where I am using jquery/ajax to load a series of buttons into a div. This script loads buttons every time the user scrolls the page and each button should run a jquery function when clicked. The problem arises when I switche ...

Add CSS styles to the outermost container element when the slideshow is currently in use

On my homepage, I have a carousel featuring multiple slides. However, when the third slide appears in the carousel, the positioning of the carousel buttons within the div class="rotator-controls" shifts downward due to the space taken up by the image. My o ...

What steps should I take to resolve the issue with my various layouts in Thymleaf?

Encountering an issue while trying to incorporate another fragment from a layout page that contains two fragments. One is for the header and the other for a post form. Including just the first one results in a problem, but adding the second one leads to tw ...

Effortlessly Concealing Numerous Elements with a Single Click in Pure JavaScript

I have successfully created an HTML accordion, but I am facing an issue. I want to implement a functionality where clicking on one accordion button will expand its content while hiding all other accordion contents. For example, if I click on accordion one ...

Every symbol located at the top of the <td> element

SOLVED by P. Leger: In my CSS I just modified the vertical-align property to top, which successfully resolved the issue for me I am working on creating a basic schedule system where the admin has the ability to manage users and assign them to specific dat ...

What are the steps to ensure a form does not trigger the action URL and instead only prints the data upon submission

Currently, I am working on creating a form that will submit without opening the action URL when a button is clicked. Additionally, after submission, I want to display a message and clear the form. Can anyone guide me on how to achieve this? <form id="c ...

Does JSON.Stringify() change the value of large numbers?

My WCF service operation returns an object with properties of type long and List<string>. When testing the operation in a WCF application, everything functions correctly and the values are accurate. However, when attempting to call the service using ...

Issue with the initial element in CSS and the cause remains a mystery

"first of type" dont like to work: .elements { width:70%; margin:0 auto; display:flex; flex-direction: column; .addElement { width:280px; text-align: center; border:1px solid black; font-family: ...

Struggling to get JQuery timing events to function properly?

Encountering timing issues with the events in my self-made simon memory game. Experimented with setTimeout but struggling to figure out which events to time and the appropriate duration for them to be distinguishable. $('#play').click(function( ...

What could be preventing my HTML replacement assignment from functioning properly?

Whenever a choice is made, I want to substitute the current content with different content. My current attempt is to update the content from "HuckFinn" to "Tom Sawyer will be added later" when the user selects "Tom Sawyer" from the drop-down menu. However, ...

Error encountered: Class not found exception in the context of JSONArray

import org.json.JSONArray; JSONArray json=new JSONArray(al); response.setContentType("application/json"); response.getWriter().print(json); } Despite having included the necessary jar in my project, I am encountering this error: SEVERE: Servle ...

Strange HTML antics

On my website, I encountered an issue when trying to register without entering any information into the required fields. The errors were correctly displayed in this screenshot: https://i.sstatic.net/wrxjt.png However, after inserting random characters in ...

Issue with CSS styling on a content slider causing the last picture to display incorrectly

I recently updated a Content Slider and tweaked the styles to my preference. Check out the changes I made on this link. In addition, I included an extra Thumbnail Picture on the right (7th one) along with the Main Picture. Oddly enough, the Slider seems ...

JavaScript counter unexpectedly resetting to zero instead of the specified value

After gathering feedback from voters: My current issue revolves around a Java counter I created. Ideally, the numbers should start at 0 and increment to the specified number upon page load. You can see an example of this functionality here: https://codepe ...

Determining the height of the error container using jQuery validate

I am having difficulty retrieving the height of the error container when using the 'jquery validate' plugin to submit a form with errors. The height value of the error container is not displaying and the alert box is not working. Can someone prov ...

Closing an Electron Dialog triggers a refresh on my current page

I currently have an Electron application in place. It utilizes Bootstrap v4, Electron v2, as well as other node modules. One concern I am facing is related to a button that triggers an Electron dialog box where users can select a folder. Upon selecting th ...