Displaying a div and ensuring it remains visible upon clicking

$(document).ready(function() {
  $('#input').focusin(function() {
    if ($(this).val() != '') {
      $('#div').show();
    } else {
      $('#div').hide();
    }
    $('#input').keyup(function() {
      // If not empty value, show div
      if ($(this).val() != '') {
        $('#div').show();
      } else {
        $('#div').hide();
      }    
    });
  });
  $('#input').focusout(function() {
    $('#div').hide();

  });

});
#div {
  display: none;
  position: absolute;
  bottom: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='div'>
  <a href='website.com'>Link From AJAX<a>
  <a href='website.com'>Link From AJAX<a>
  <a href='website.com'>Link From AJAX<a>
</div>
<input id='input' type='text'>

In this code snippet using jQuery, the #div element is set to display when text is entered inside the #input. However, clicking on the #div causes it to disappear and prevents the link from working properly.

To resolve this issue and keep the #div displayed when either the #div or #input elements are clicked, an additional line of code within the .focusin function can be added. Additionally, removing the position and bottom CSS properties will help fix the previous error.

The problem with the disappearing #div is related to the position: absolute; bottom 20px line in the CSS styling.

After updating the code with the necessary adjustments, the functionality worked as intended, ensuring that the #div remains visible when focused on the correct elements while hiding it when outside elements are interacted with.

Answer №1

To prevent the effect of the focusout handler, you can set a flag:

var hideFlag = false;
$(document).ready(function() {
  $('#input').keyup(function() {
    // Display div if input is not empty
    if ($(this).val() != '') {
      $('#div').show();
    } else {
      $('#div').hide();
    }
  });
  $('#div a').hover(
    function() { hideFlag = true; },
    function() { hideFlag = false; $('#input').focus(); }
  );
  $('#input').focusout(function() {
    if(!hideFlag) {
      $('#div').hide();
    }
  });
});
#div {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='div'>
   <a href='#'>Hello World</a>
</div>
<input id='input' type='text'>

Answer №2

When the input loses focus, make sure to check if the active element is the DIV, and hide it if it's not.

Additionally, when positioning an element absolutely, be sure to assign a z-index so that it remains clickable. Otherwise, the click event will be triggered on the element in its normal position at that location.

$(document).ready(function() {
  $('#input').focus(function() {
    if ($(this).val() != '') {
      $('#div').show();
    } else {
      $('#div').hide();
    }
  }).blur(function() {
    if (!$("#div").is(":focus,:active")) {
      $("#div").hide();
    }
  });
  $('#input').keyup(function() {
    // If not empty value, show div
    if ($(this).val() != '') {
      $('#div').show();
    } else {
      $('#div').hide();
    }
    var search = $('#input').val();
    $.post('search.php', {
      search: search
    }, function(data) {
      $('#div').html(data);
    });
  });
});
#div {
  display: none;
  position: absolute;
  bottom: 20px;
  z-index: 2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='div'>
  <a href='www.someplace.com'>Hello World</a>
</div>
<input id='input' type='text'>

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

Modify the background color of each word within the search bar

I've been attempting to colorize each word using jQuery and give them a colored background. I came across a solution, but it only seems to work for the HTML content, not the input field in the search bar. Below is an example of what I found: HTML So ...

Interact with database using Ajax and Codeigniter (utilizing Bootstrap modal)

My goal is to create an advanced search feature with an interactive button that opens input fields and dropdown menus. To populate these dropdown menus with data from the database without overloading the page, I plan to use AJAX when the user triggers the ...

Encountering an Issue Retrieving User Orders - Receiving 401 (Unauthorized) Status Code

I am currently working on a React project focused on displaying user orders. I have successfully integrated JSON Web Tokens (JWT) for user authentication. However, I keep encountering a persistent 401 (Unauthorized) error when trying to retrieve the user&a ...

Tips for sending arguments to an async function

I am currently facing an issue in my vue.js application where I am struggling to access the value of name that is being passed to my function. My hunch is that this issue is related to scope. After some research, it seems like using a fat arrow function mi ...

Limit the length of text using jQuery by specifying the maximum pixel width

Trying to utilize jQuery for a quick function that calculates the pixel width of a string on an HTML page and then shortens the string until it reaches a desired pixel width... Unfortunately, I'm encountering issues with this process as the text is n ...

Unsure of the response from the $.post request

CHANGE: I keep receiving the object {"readyState":1}. Why is this happening? How can I successfully retrieve the result from the $.post (specifically, the object {"result":"ERROR"})? This pertains to using jEditable. (Please note: This seems more like a ...

The collision function is currently not functioning properly, causing a hindrance in movement. There are no other codes restricting movement

const rightPressed = false; const leftPressed = false; const upPressed = false; const downPressed = false; const players = []; players[0] = new victim(1234); const arrayw = 50; const arrayh = 50; const canvas = document.getElementById("myCanvas"); const ...

An unidentified error occurred while making an AJAX call to web methods on the localhost webform

Having an issue with calling two webmethods in a webform class using JQuery AJAX. I keep receiving an Unknown web method error, even after trying to make the webmethods public and static. This is just local testing. Any assistance would be appreciated, tha ...

Leveraging the variables declared within functions.php in WORDPRESS

I am facing an issue with a variable that is being retrieved from jQuery into php in my functions.php file. Unfortunately, I am unable to utilize it on a page. When I try to echo it from functions.php, it shows up in the console in chrome, but with a 0 a ...

Is there a way to reposition a popup window to the center of the page after launching it?

popup = window.open(thelink,'Facebook Share','resizable=1,status=0,location=0, width=500,height=300'); My goal is to perfectly center this popup window both vertically and horizontally. ...

Here's a method of sorting through an array of objects and displaying all objects that include a specific keyword in one of their values

I am currently working on a project involving an array of book objects. My task is to display a list of all books that have either "companies" or "people" in their title using console.log. const books = [{ title: 'How to win friends and influence ...

Creating distinctive identifiers for individual function parameters in JavaScript using addEventListener

I am working on a for loop that dynamically generates elements within a div. Each element should trigger the same function, but with a unique ID. for(var i = 0; i < 10; i++) { var p = document.createElement("p"); var t = document. ...

Position the text in the exact center of an HTML element using absolute positioning

Hey there! I am currently working on a website and I'm trying to create a simple delete button that can be used throughout the site. However, I'm having trouble getting it positioned correctly... Here's what I have so far: <button id="c ...

Validating Credit Card Numbers with Spaces

Currently, I am in the process of creating a credit card form that requires validation using checkValidity to match the specific card pattern that is dynamically added to the input field. For example, if a user enters a Mastercard number such as 545454545 ...

retrieve data for chart from an AJAX request

I am looking to create a chart using amCharts and I have received some values from the server through an ajax call. Now, I need help in utilizing this data for my chart. Can anyone guide me on how to achieve this? var chart = am4core.create("chartdiv& ...

Determine the name of the time zone using JavaScript

Currently, I am developing a React application and facing an issue where the timezone is detected as 'Etc/GMT-1' instead of the desired format 'Africa/Bangui'. This problem seems to be specific to my machine as it persists even when usi ...

Guide to transferring existing Mongoose Schema information to updated Mongoose Schema Data

In the schema I was using previously with Mongoose, it looked like this: social:{ instagram: String, facebook: String, whatsapp: String, } Now, my updated Mongoose Schema is structured differently: social:{ instagram: { dat ...

Adjust the size of an event in the Angular Full Calendar with Chronofy, while utilizing constraints to control the drag and drop functionality

I'm currently in the process of developing an availability calendar for scheduling meetings during open times. If a time slot is unavailable, users should not be able to place an event there. While I have successfully implemented this feature, I am ...

Optimal Method for Extracting Data from Websites: Discovering URLs through Chrome Network Tools?

Here is a webpage link and screenshot of network tools displaying the action when you click download csv. What's the most effective way to write a Python script that retrieves the data previewed? https://i.sstatic.net/KCiIIlGy.png ...

The z-index property seems to be disregarded

I'm facing an issue with my navigation dropdown menu. I want the dropdown items to appear from behind the menu, but they always come from the top. I've tried adjusting the z-index but it doesn't work. I've checked similar problems onlin ...