Having trouble with the focusout() function not registering on the search box?

When using the focusout function, I encountered an issue where clicking on a title in the search results would prevent redirecting to the title page. Although the function worked properly when closing the search results by clicking on a different element on the page, the results also closed when clicked on.

I attempted using the blur function as well as hide() and show(), but the outcome remained the same. Even though I have set .result display to none, it should not hinder me from selecting a search result. What could be causing this issue?

// jquery.js

$(document).ready(function() {
  $('.search-box input[type="text"]').on("keyup input", function() {
    /* Get input value on change */
    var inputVal = $(this).val();
    var resultDropdown = $(this).siblings(".result");
    if (inputVal.length) {
      $.get("includes/searchbar.inc.php", {
        term: inputVal
      }).done(function(data) {
        // Display the returned data in browser
        resultDropdown.html(data);
        $('.result').css('display', 'block');

        $("#searchboxy").focusout(function() {
          $('.result').css('display', 'none');
        });
        $("#searchboxy").focusin(function() {
          $('.result').css('display', 'block');
        });

      });
    } else {
      resultDropdown.empty();

    }
  });

  // Set search input value on click of result item
  $(document).on("click", ".result", function() {
    $(this).parents(".search-box").find('input[type="text"]').val($(this).text());
    $(this).parent(".result").empty();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- header.php -->

<div class="search-box" id="searchboxy">
  <input type="text" autocomplete="off" placeholder="Search for a game or genre..." />
  <div class="result" id="resultsearch"></div>
</div>

Answer №1

The issue with your code was the focusout event handler triggering every time the search input lost focus, including when clicking on the results.

This caused the click event on the results to be triggered after the hide action in the first handler, preventing it from working as intended.

To address this, a better approach is to attach a click event handler to the entire document and check if the clicked element has the parent #searchboxy. If it does, hide the results; otherwise, leave them visible.

In the demo, I simulated a custom result from your API without clear data, which you displayed without manipulation.

I also revised how you captured click events on the result items by attaching the event handler once to the parent results.

// Your fetch replaced with an unreachable URL
const makeSearch = (term) => {
  return new Promise((resolve, reject) => {
    resolve(`
      <ul>
        <li>Result1</li>
        <li>Result2</li>
        <li>Result3</li>
      </ul>`
    );    
  });
}

// Click event on the document
$(document).on('click', function(event){  
  // Hide .result if clicked element doesn't belong to #searchboxy group
  if(!event.target.closest('#searchboxy')){
    $('.result').css('display', 'none');
  }
});

// Show .result on input text focusin
$("#searchboxy").on('focusin', function() {      
  $('.result').css('display', 'block');
});

// Click event on .result box...
$(document).on("click", ".result", function(event) {  
  const textOfClickedResultElement = event.target.innerText;  
  $(this).parents(".search-box").find('input[type="text"]').val(textOfClickedResultElement);
  $(this).parent(".result").empty();
});

$(document).ready(function() {

  $('.search-box input[type="text"]').on("keyup input", function() {
    /* Get input value on change */
    var inputVal = $(this).val();
    var resultDropdown = $(this).siblings(".result");
    if (inputVal.length) {
      
      //$.get("includes/searchbar.inc.php", {
      //  term: inputVal
      //})
      
      // Replaced search request for demo purposes
      makeSearch(inputVal)
        .then(function(data) {          
          // Display returned data in browser
          resultDropdown.html(data);
          $('.result').css('display', 'block');
        });
    } else {
      resultDropdown.empty();
    }
  });
  
});
.info{
  margin-bottom: 10px;
}

#searchboxy{
  border: dashed 3px lightgray;
  padding: 10px 10px;
}

#searchboxy input{
  width: 15rem;
}

#resultsearch{
  border: solid 1px gray;
  display: none;
  margin-top: 1rem;
}

#resultsearch li{
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="info">
  Start typing inside the textbox to show the search results.<br>
  Clicking anywhere outside the dashed borders will hide the results.<br>
  Giving focus to the textbox will show the results.<br>
  Clicking any single result item will push its value into the search box.
</div>

<div class="search-box" id="searchboxy">
  <input type="text" autocomplete="off" placeholder="Search for a game or genre..." />
  <div class="result" id="resultsearch"></div>
</div>

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

Angular - CSS Grid - Positioning columns based on their index values

My goal is to create a CSS grid with 4 columns and infinite rows. Specifically, I want the text-align property on the first column to be 'start', the middle two columns to be 'center', and the last column to be 'end'. The cont ...

403 error: jQuery Ajax POST denied

I'm encountering an issue while trying to execute a simple ajax post using jQuery: $.ajax({ type: 'POST', url: "ucUploadDownloadCommand.ascx/UploadXLSFile", data: "{}", dataType: 'json', contentType: "application/json; c ...

The deletion request using the form in Express is experiencing issues and not functioning properly

When attempting to delete data from a database using a form in node.js and express, I am encountering issues with the deletion process. It seems that there are only two methods available - get and post - and no specific delete method. router.js code rout ...

Which specific CSS attributes should be applied to create a scroll bar within this table?

Below is the table that I am working with: 'table' I want to ensure that its width remains the same even when the screen size is reduced, and only add a scroll bar to view it. I have already included overflow: scroll; in the container <div> ...

Ensure that the Materialize CSS modal form remains open even after submission

Is there a way to reload a form inside a materialize modal with empty fields without closing the modal after submitting? The issue is that currently, when the submit button is clicked, the modal closes and redirects. <div class="modal" id="docM ...

Having an Issue with the jQuery .get Method

Here is some HTML code I have <ul> <li> <a href='#' class='approch' alt='1' > 111111 </a> </li> <li> <a href='#' class='approch' alt='2' > 222222 < ...

Scrape embedded content within an IFrame on a webpage with Java

Currently, I am interested in crawling the dynamic content within an IFramed webpage; Unfortunately, none of the crawlers I have tested so far (Aperture, Crawl4j) seem to support this feature. The result I typically get is: <iframe id="template_cont ...

Retrieve the jquery.data() of an element stored in an HTML file using JavaScript or jQuery

I have a dilemma with storing HTML in a database for later retrieval. Imagine the HTML being a simple div, like this: <div id="mydiv">This is my div</div> To store related information about the div, I use jQuery.data() in this manner ...

Displaying each character of text individually with jQuery

I am trying to display the text within a ul tag one by one when hovering over some text. However, I am encountering an error. How can I resolve this issue? You can view the code for mouseover functionality by hovering over the "hover here hover again" lin ...

What can be done to stop a header from sticking to a table and displaying horizontally scrolling content along the border?

I need to ensure that the red headers do not overlap with the blue headers' borders while scrolling horizontally. It is essential for me to have a white border on the blue headers. .container { overflow: auto; width: 200px; } table { borde ...

What steps do I need to take in order for my web controls to show up on top of an activex

I'm currently facing a challenge in designing a website with activex reports. Even though I recommended switching to another reporting tool or technology, we're still using activex for now. I've noticed that graphical activex objects displa ...

Can a single value be stored in a table using a radio button?

I have created an HTML table that is dynamically generated from a database. I am using a for loop to populate the table. However, I am facing an issue where each radio button in the table holds only one value. What I actually want is for each row to have ...

What is the best way to place a parent div above its child element?

I'm currently dealing with a container div styled with background-color: red;. This container has around 12 children, and the last child is set with background-color: blue;. My goal was to position the container on top of the child with the blue backg ...

Step-by-step guide on inserting an image directly into an HTML file without utilizing LinkedResource or CDO

Let's say we have a scenario: My objective is to put together an HTML file with an embedded image, similar to the structure below: <html> <head> </head> <body> <img src="?" /> </body> </html> The quest ...

Ways to emphasize the index navigation link when on the main page

Currently, there is a web design project that I am tackling and have encountered a slight hiccup that needs resolving. The issue revolves around highlighting different navigation links based on the URL of the current page. This functionality works seamless ...

The Autoprefixer script crashes with the error message: TypeError - Patterns can only be a string or an array of strings

After successfully installing autoprefixer and postcss-cli, I embarked on setting up a simple build process with NPM scripts using my command prompt and VS code. As someone with only 2 months of coding experience, I was following a tutorial on CSS/SASS top ...

Unique rewritten text: "Displaying a single Fancybox popup during

My website has a fancybox popup that appears when the page loads. I want the popup to only appear once, so if a user navigates away from the page and then comes back, the popup should not show again. I've heard that I can use a cookie plugin like ht ...

Adjusting the background color of an individual element within a grid using CSS

<div id="56c46f8385953" class="mg_box mg_pre_show col1_3 row1_3 m_col1_2 m_row1_3 mgi_14 mg_pag_1 mg_gallery mg_transitions mg_closed " rel="pid_14" mgi_w="0.333" mgi_h="0.333" mgi_mw="0.5" mgi_mh="0.333" > <div class="mg_shadow_div"> ...

The jQuery slider does not abruptly halt when the mouse is clicked and released

Trying to create a smooth sliding effect on a jQuery slider, but facing issues with responsiveness. When I decrease the interval time in `setInterval` to 200, the slider doesn't immediately respond to `mouseup` events and the slides stop moving after ...

CSS Switchable Style Feature

I am in need of some assistance with the navigation on my website. You can find the current code at this link: http://jsfiddle.net/Sharon_J/cf2bm0vs/ Currently, when you click on the 'Plus' sign, the submenus under that category are displayed bu ...