Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS selector for div containing an input with focus

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?

like image 497
TheIronCheek Avatar asked Dec 23 '22 13:12

TheIronCheek


2 Answers

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>
like image 67
Blazemonger Avatar answered Dec 29 '22 10:12

Blazemonger


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>
like image 45
sol Avatar answered Dec 29 '22 09:12

sol