I have a link at the top of a page that when hovered over, displays a search menu.
#dropdown {
display: none;
}
li:hover #dropdown {
display: block;
}
<ul class="nav navbar-nav">
<li><a href="">Link 1</a></li>
<li><a href="">Link 2</a></li>
<li>
<a href="">Search</a>
<div id="dropdown">
<input name="txtSearch" type="text" id="txtSearch" class="form-control" />
<input type="submit" name="btnSearch" value="Search" id="btnSearch" class="btn" />
</div>
</li>
</ul>
Since there is a text box inside the dropdown <div>
, I want the dropdown to stay visible even while unhovered if the user is typing in the text box.
Is there a pure CSS way to do that?
You can add the :focus-within
pseudo-class to any parent element.
li:hover #dropdown,
li:focus-within #dropdown {
display: block;
}
However, keep in mind this is not supported in Microsoft browsers. You'll need a JavaScript-based solution for that. Here's one that uses jQuery:
$(document).on('focus','#txtSearch,#btnSearch',function(e) {
$(this).closest('li').addClass('hover');
}).on('blur','#txtSearch,#btnSearch',function(e) {
$(this).closest('li').removeClass('hover');
});
#dropdown {
display: none;
}
li:hover #dropdown,
li.hover #dropdown {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="nav navbar-nav">
<li><a href="">Link 1</a></li>
<li><a href="">Link 2</a></li>
<li>
<a href="">Search</a>
<div id="dropdown">
<input name="txtSearch" type="text" id="txtSearch" class="form-control" />
<input type="submit" name="btnSearch" value="Search" id="btnSearch" class="btn" />
</div>
</li>
</ul>
You can use the focus-within
pseudoclass here.
Info from MDN
Supported browsers
#dropdown {
display: none;
}
li:hover #dropdown {
display: block;
}
#dropdown:focus-within {
display: block;
}
<ul class="nav navbar-nav">
<li><a href="">Link 1</a></li>
<li><a href="">Link 2</a></li>
<li>
<a href="">Search</a>
<div id="dropdown">
<input name="txtSearch" type="text" id="txtSearch" class="form-control" />
<input type="submit" name="btnSearch" value="Search" id="btnSearch" class="btn" />
</div>
</li>
</ul>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With