How can you make sure a div stays visible while a user is interacting with it or an input field?

I am looking to create a functionality where a div is displayed under an input field when the user clicks on or focuses on the input field. The div should be hidden when the focus is removed or when the user clicks outside of the input field or the div itself. In this specific example, clicking on the input field displays the div, and clicking outside of the input field hides it.

However, I want the div to remain visible under certain conditions:

1. When the input field is focused/clicked.
2. When the click event occurs within the div(.options).

The div should only be hidden when:

1. The input field loses focus and the click event is not within the div.
2. The click event occurs outside of the div.

Click here for the Fiddle URL

Answer №1

To implement the use of relatedTarget, you can follow this method:

$(function () {
    var inputField = $('#input_field');
    var optionsResult = $('#options');

    inputField.focusin(function (e) {
        e.preventDefault();
        optionsResult.show();
    }).focusout(function (e) {
        if(e.relatedTarget){
          if(e.relatedTarget.tagName != 'A')
            optionsResult.hide();
        }
        else{
          optionsResult.hide();
        }
    });
});

$(document).on('click', function(e){
  if(e.target.tagName == 'HTML'){
    $('#options').hide();
  }
});
.options{
  display:none;
  position: absolute;
  float: left;
  width: 300px;
  height: 200px;
  background: #eee;
}
a{
  display:block;
  float: left;
  width: 100%;  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="app">
  <div class="header">
    <div id="main_container" class="box">
      <div class="inputs">
        <input id="input_field" type="text" placeholder="Demo account"/>
      </div>
      <div id="options" class="options">
        <a href="#">Common Link</a>
        <a href="#">Common Link 2 </a>
      </div>
    </div>
  </div>
  <div class="Data">
  Another Data Set
  </div>
</div>

Answer №2

Ensure that the body tag encompasses your application and spans the entire width and height of the window. Implement an event listener to detect if a click event occurs outside of the options division and not within the input field. If this is the case, hide the options division.

Check out the JsFiddle example here

body {
  height: 100vh;
  width: 100%;
}
$(function () {
    var inputField = $('#input_field');
    var optionsResult = $('#options');
    var options = document.querySelector('#options');

    // Set up a click event listener on the body
    document.body.addEventListener('click', function (event) {
      // Hide options if the click is outside of the options div and not on the input element
      if (!options.contains(event.target) && event.target.id !== 'input_field') {
        optionsResult.hide();
      }
    });

    inputField.focusin(function (e) {
        e.preventDefault();
        optionsResult.show();
    });
});

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

Invisible anchor rows in GWT's UIBinder grid view

While developing my GWT application, I encountered an issue in a composite class where I am creating a Grid UI binder. Each cell of the grid contains an anchor UI Binder element. However, upon loading the page in the application, I noticed that the table w ...

A layout featuring a grid design that includes spacing and gutters between items, however, there is no spacing between the items

I am looking to create a grid layout where each child element represents an individual grid square. However, I am facing an issue with spacing between the children and the parent container, which is not desired. How can I eliminate this unwanted space? U ...

Top storage solution for ExpressJS in the world of NodeJS

Embarking on the journey of creating my first substantial NodeJS application. My primary focus is achieving top-notch performance as the project involves a large AJAX (AngularJS) interface with numerous requests from multiple users. Currently in the proce ...

Failed commitments in JavaScript without a catch block (unhandled rejection)

When working on my project in VueJs JavaScript, I want to be able to see console messages if any of my Promises are not fulfilled and do not have a catch block. I attempted using the following code: Promise.reject("error!"); window.addEventListener(&apos ...

Incorporating Javascript into HTML

I have developed a script to randomly change the size of an element, but I am struggling to understand how to incorporate it using HTML or iframe code for randomization. <script type="text/javascript"> var banner1 = ["728", "90"]; var banne ...

What steps can I take to stop my html table from expanding beyond its intended size

There are instances where the length of a data piece in one of my table cells causes it to expand and distort the overall layout of the table. Is there a way to avoid this from happening? ...

Using a double border causes the div to appear bigger in size

I'm currently working with React and Tailwind CSS, and I have a specific design goal in mind: https://i.sstatic.net/rbVP1.png To achieve this, I added borders to both the + and - buttons, as well as a border on the parent div to encompass all elemen ...

Adjusting the CSS link using jQuery isn't as effective as expected

I am in the process of developing a web application that users will use in the field, and they have requested the ability to manually switch between light and dark styles based on the ambient lighting conditions. I am utilizing jQuery for this project. I ...

Disappear element after a brief moment

What is the best way to temporarily hide an element and then have it reappear after a second? var targetElement = document.getElementById("myElement"); targetElement.onclick = function() { this.style.display = "none"; setTimeout(function(){ ...

The elements within the side navigation menu are not displaying correctly within the app component's HTML file

In my Models.ts file, I created a code that requires me to call the headers in side-nav.component.ts to app.component.html. However, when I try to call app.index.html by typing <side-nav><side-nav>, the component seems to be not specific. mode ...

When you use jQuery's serialize() method on a form element, it will only serialize one form element at a time

Consider the form below: <form id="form" name="form"> <input name="name"/> <input name="version"/> <input name="template"/> <textarea name="elements"></textarea> <textarea name="features"></textarea> <tex ...

What could be causing my floated list items to stack on top of each other

Typically, I am able to troubleshoot my way out of any CSS dilemma, but this particular issue on Friday afternoon has me stumped! Click here to see the problem. Hover over the menu items (birthday, wedding, etc.) and notice the dropdown effect. Initially ...

What is the best way to transfer a content script variable to a background script in a Chrome Extension?

I am looking to transfer a variable named "website_hostname" from the content script to the background script. This variable holds the hostname of the website you are currently visiting. Content Script: var website_hostname = window.location.href; //Cod ...

Ways to retrieve information from a URL using the .get() method in a secure HTTPS connection

As I work on handling user input from a form using node.js, express, and bodyParser, I encounter an issue. Even after using console.log(req.body), the output is {}. This is puzzling as there is data in the URL when the form is submitted successfully at htt ...

Is it necessary to send form data back with Express, or is there an alternative solution?

I am facing a simple problem with my handlers for /login get and post requests. Here is the code: loginRender(req, res) { let options = { title: 'Login', layout: 'auth.hbs' } res.render('login', options) } logi ...

If the key for an object is already in existence, then append another object to

Currently, I am parsing through a considerable JSON file and handling key:value pairs within an object. The problem arises when I encounter a key that requires me to append another object to it, rather than simply overwriting it. For instance: var collec ...

Margin isn't functioning properly

My section is not centered and adding margin-left doesn't seem to be working. Any suggestions on how I can solve this? Take a look at how it appears. Here's the code: .margins { margin-left: 100px; } <link href="https://cdn.jsdelivr.net ...

What are the essential files required to begin with d3.js?

Starting off with d3.js, I've downloaded the newest version from https://github.com/dc-js/dc.js/releases. Along with the d3.js file, there are plenty of other scripts located in the src and spec directories. Is it necessary to move all of these files ...

Tips for safely sanitizing an HTML file containing both HTML tags and JavaScript functions within an Angular application

I am trying to bind an HTML file that contains both HTML and JavaScript (jQuery) functions into my Angular application. Here is how I bind my HTML file into the component's HTML: <div [innerHTML]="currentDetailEntry?.content | sanitizeHtml">&l ...

Could you explain the purpose of the app.use(cors()) function call?

I'm aware that accessing an API with a different domain than our own is not allowed. Nonetheless, I often observe individuals incorporating the cors module into their Express.js applications in order to interact with APIs and then utilizing it in this ...