To close the menu, simply tap on anywhere on the screen

Is there a way to modify a script so that it closes the menu when clicking on any part of the screen, not just on an 'li' element?

$(function() {
  $('.drop-down-input').click(function() {
  $('.drop-down-input.selected').removeClass('selected'); // Clear previous selection
  $(this).addClass('selected');
  $(this).find(".dropdown-list").show();
});

$(document).on("click", ".drop-down-input.selected li",
  function(e) {
    e.stopPropagation();
    $('.drop-down-input.selected .dropdown-list').hide().siblings().val($(this).html());
  });
});

This is my HTML code:

<div class="styled-input-container drop-down-input">
                       <input id="simple_2" class="drop-down-select" placeholder="input text" type="text">
                       <ul class="dropdown-list">
                           <li>eeee</li>
                           <li>xxxx</li>
                           <li>xxxx</li>
                           <li>xsssxxx</li>
                       </ul>
                   </div>

Answer №1

Here's a functional solution that may be of assistance :)

$( document ).ready(function() {
    
    // Changing input color from grey to blue
    
    
  $(".styled-input-container input").focus(function () {
     $id = this.id;
     $idgen = '#' + $id;
     //console.log($idgen);
     
     $($idgen).closest( "div" ).addClass('focused');
    });
    
    $(".styled-input-container input").blur(function() {
        $('.styled-input-container').removeClass('focused');
        
    });
  
    // Opening and closing ul list input
    
   $(function() {
        $('.drop-down-input').click(function() {
            $('.drop-down-input.selected').removeClass('selected'); // Clear previous selection
            $(this).addClass('selected');
            $(this).find(".dropdown-list").show();
        });

        $(document).on("click", ".drop-down-input.selected li",
          function(e) {
            e.stopPropagation();
            $('.drop-down-input.selected .dropdown-list').hide().siblings().val($(this).html());
          });
    });

    $(document).mouseup(function (e){
        var container = $(".dropdown-list");

        if (!container.is(e.target)
            && container.has(e.target).length === 0)
        {
            container.hide();
        }
    });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="styled-input-container">
    <input id="simple_1" placeholder="Enter text here" type="text">
                   
</div>
<div class="separator"></div>
<div class="styled-input-container drop-down-input">
    <input id="simple_2" class="drop-down-select" placeholder="Enter text here" type="text">
    <ul class="dropdown-list">
        <li>eeee</li>
        <li>xxxx</li>
        <li>yyyy</li>
        <li>zzzz</li>
    </ul>
</div>

Answer №2

To implement a listener on the entire DOM, simply use the following code:

$(document).on('click', ':not(.drop-down-input.selected li)',function() {/* Close all open menus  */});

This approach allows you to exclude certain elements, such as the li element, from being trigger by the click event using the :not selector.

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

jQuery Mobile: PHP dynamically loads content (forms) but styles do not apply

Issue: jQuery Mobile themes are not being applied to dynamically inserted forms. Forms are successfully inserted into the <div id="formSuccess">. Dynamic forms are generated using a PHP script. The project utilizes jquery.mobile- ...

Stop users from skipping ahead in an HTML5 video

Struggling to stop a user from seeking on the video player. I've attempted to bind to the event, but it's not working as expected. Any suggestions on how to successfully prevent this action? @$('#video').bind("seeking", (e) =& ...

Controller encounters a error when requiring a module

Struggling to set up Stripe for my app, I've encountered some issues with the module implementation. Typically, I would require a module at the top of the file to use it. However, in the paymentCtrl file, when I do this, it doesn't work and I rec ...

Struggling to retrieve the JSON information, but encountering no success

Here is the javascript code snippet: $.getJSON("validate_login.php", {username:$("#username").val(), password:$("#password").val()}, function(data){ alert("result: " + data.result); }); And here is the corresponding php code: <?ph ...

Tips for displaying an image larger than its container using CSS or Bootstrap

I'm attempting to include an image on the left side of text within a dark container. However, I want the picture to start at the very bottom of the container and extend above the top of the container, so that the image appears outside the top of the c ...

Utilize PHP SVG images to trigger internal JavaScript code through the <img> tag

Here is a php function that generates an SVG image. public function actionJsTest() { header('Content-Type: image/svg+xml'); $svg = ''; $svg .= '<svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/ ...

Checking the opacity with an if/else statement, then adding a class without removing the existing class

This function is designed to check the opacity of the header, which fades out as a user scrolls down. If the opacity is less than 1, it disables clickability by adding the class "headerclickoff". However, there seems to be an issue with removing the clas ...

Tips for handling a JSON payload retrieved through a POST request

I'm currently working on a button that triggers a POST call to retrieve a json response from the server. My goal is to display this json response in a new (chrome) browser tab. Here's what I have so far using Angular: $http.post(url, data) .t ...

The overflow-anchor property is not effective for scrolling horizontally

My goal is to create a never-ending horizontal scroll that allows users to scroll both left and right. When users scroll to the left, new content should be added to the beginning of the scrollable element (similar to scrolling through a schedule history). ...

Determining the precise location of the div element

I am seeking to determine the precise positions of a div based on its class name. In the screenshot provided, my script for finding the div's position is highlighted in yellow, while the div I am targeting is highlighted in red at the bottom. Currentl ...

Custom options titled MUI Palette - The property 'primary' is not found in the 'TypeBackground' type

I am currently working on expanding the MUI palette to include my own custom properties. Here is the code I have been using: declare module '@mui/material/styles' { interface Palette { border: Palette['primary'] background: Pa ...

Ensuring a div remains perfectly centered

Currently, I am new to HTML and still in the process of learning. I am facing a challenge in centering a button within a div, and I have been using margins to position it. While this method works well when the window is fullscreen, the button's positi ...

What methods can I use to verify that the form data has been effectively stored in the database?

Here's the code snippet I've been working on: <?php // Establishing connection to the database require("database.php"); try{ // Prepare and bind parameters $stmt = $conn->prepare("INSERT INTO clients (phonenumber, firstname) VALUES (:ph ...

How can I ensure security measures are in place to avoid XSS attacks on user-generated HTML content?

Currently, I am in the process of developing a web application that will allow users to upload entire web pages onto my platform. My initial thought was to utilize HTML Purifier from http://htmlpurifier.org/, but I am hesitant because this tool alters the ...

Find the sum of values in an array of objects if they are identical

[{ingName: "milk", quantity: "1.5", unit: "cups"}, {ingName: "sugar", quantity: "0.25", unit: "cups"}, {ingName: "vanilla extract", quantity: "1.0", unit: "tsp&quo ...

What is the procedure for invoking a function when the edit icon is clicked in an Angular application

My current Angular version: Angular CLI: 9.0.0-rc.7 I am currently using ag-grid in my project and I encountered an issue when trying to edit a record. I have a function assigned to the edit icon, but it is giving me an error. Error message: Uncaught Re ...

When scrubbing through videos, Chrome consistently throws a MEDIA_ERR_DECODE error

Encountering a MEDIA_ERR_DECODE error while scrubbing in Chrome on two different PCs. One PC runs Windows 7 with Chrome version 26, and the other runs Windows 8 with Chrome version 27. This issue occurs across all videos. When attempting to scrub on the v ...

Tips for setting up my ajax/views method to output a dictionary

Here's the HTML snippet I have along with an AJAX request: <script> $("#search_button").on("click", function(){ var start_date = $("input[name=\"startdate\"]").val(); var end_date = $("input[name=\"end ...

jQuery mistakenly sends a GET request instead of a POST request

Has anyone encountered an issue where attempting to send a POST request to Flask using jQuery results in a GET request instead? This is a new problem for me, and I'm unsure why it's happening. jQuery system_data = { "system_name":"system_name ...

"Troubleshooting issues with Material Design components in AngularJS: Why is <md-select> not functioning correctly

I'm attempting to implement the <md-select> tag, but I can't seem to achieve the same result as shown here. This is the code I've written: <div layout="column" layout-align="center center" style="margin: 0px 10px 0px 5px;"> & ...