Phaneroptera
Phaneroptera

Reputation: 25

Display child-element with hover, hide it when focus is lost

I have an element (dropdown-content) that is displayed when its parent (Element2) is hovered. When no interaction with the element (dropdown-content) occurs I want it to act as it does now and disappear when the hover is over. But when the element gets focus (the select or input or somewhere else in the dropdown-content are clicked) I want it to stay displayed until it loses focus (clicked somewhere outside the dropdown-content), even when the coursor leaves the dropdown-content. I have already tried to find a solution with the search and several things using CSS and/or javascript but was not able to archive what I want. Here is an example code to illustrate my problem:

.dropdown-content {
  display: none;
  position: absolute;
  border: 1px solid black;
  width: 300px;
  z-index: 1;
}

.dropdown:hover .dropdown-content,
.dropdown-content:focus {
  display: inline-block;
}
<ul>
  <li>Element1</li>
  <li class="dropdown">
    <span>Element2</span>
    <div class="dropdown-content">
      <select>
        <option>option1</option>
        <option>option2</option>
      </select>
      <input type="text">
    </div>
  </li>
  <li>Element3</li>
</ul>

I would prefer a CSS solution if there is a clean one but I am also fine with javascript, but I don't want a JQuery solution if this is possible. If this makes the solution way easier it would be also fine if the dropdown-contet just stays displayed when there is focus on the select and input only.

Upvotes: 0

Views: 1559

Answers (1)

leonheess
leonheess

Reputation: 21391

You don't need Javascript let alone jQuery for that. It can and should be done with pure CSS with the pseudo-class :focus-within.

.dropdown-content {
  display: none;
  position: absolute;
  border: 1px solid black;
  margin: -3px 0 0 3px;
}

.dropdown:hover .dropdown-content, .dropdown-content:focus-within {
  display: inline-block;
}
<ul>
  <li>Element1</li>
  <li class="dropdown">
    <span>Element2</span>
    <div class="dropdown-content">
      <select>
        <option>option1</option>
        <option>option2</option>
      </select>
      <input type="text">
    </div>
  </li>
  <li>Element3</li>
</ul>

Upvotes: 4

Related Questions