Reputation: 658
I have a div that appears underneath my search box. Though I cannot click the link within the div that appears on focus - as the search form is no longer "focused".
I'm looking to make the div appear when I'm typing in the input box and make the links clickable, but hide the div when I click anywhere else.
$("#searchInput").focusin(function() {
$("#searchResults").show();
}).focusout(function () {
$("#searchResults").hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="d-flex" action="/search">
<input id="searchInput" class="form-control me-2 border-0 search-box" type="text" name="q" placeholder="Search" autocomplete="off">
</form>
<div class="result_box">
<ul class="list-group" id="searchResults">
<a href="google.com" target="_blank">Test Search Result</a>
</ul>
</div>
What's the best way to go about achieving this functionality?
Upvotes: 1
Views: 177
Reputation: 2619
Might be not the perfect solution but it works.
$("#searchInput").focusin(function() {
$("#searchResults").show();
});
$(document).on('click', function(event)
{
let target = event.target;
if(!$(target).hasClass("link") && !$(target).hasClass("search-box"))
$("#searchResults").hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="d-flex" action="/search">
<input id="searchInput" class="form-control me-2 border-0 search-box" type="text" name="q" placeholder="Search" autocomplete="off">
</form>
<div class="result_box">
<ul class="list-group" id="searchResults">
<a class = "link" href="google.com" target="_blank">Test Search Result</a>
</ul>
</div>
Upvotes: 1