John107
John107

Reputation: 2287

Click link inside div that shows when input field is in focus

So simple CSS here to show a div when the input is in focus:

.ulclass {
  background: #f0a;
  display: none;
  height: 200px;
  width: 200px;
}
form:focus-within + ul.ulclass {
  display: block;
}
<form>
  <input type="text" value="Enter some text here" class="inputclass">
</form>
<ul class="ulclass">
  <a href="https://google.com">link</a>
</ul>

I have a link inside the div being shown, however I'm not able to click it because doing so blurs the input field before the link is fired. Anyone got any suggestions on how to do this better?

Upvotes: 1

Views: 832

Answers (2)

Scott Marcus
Scott Marcus

Reputation: 65808

You can display the div with JavaScript, not CSS. Also, separate out the display:none; instruction into its own CSS class, so that it can be removed without also removing the rest of the style.

This approach is standard and will work in all clients.

document.querySelector("input.inputclass").addEventListener("focus", function(){
  document.querySelector(".ulclass").classList.remove("hidden");
});
.ulclass {
  background: #f0a;
  height: 200px;
  width: 200px;
}

.hidden {  display: none; }
<form>
  <input type="text" value="Enter some text here" class="inputclass">
</form>
<ul class="ulclass hidden">
  <a href="https://google.com">link</a>
</ul>

Upvotes: 2

Jenian
Jenian

Reputation: 592

Add the ulclass with a :hover pseudo class to the focus rule:

.ulclass {
  background: #f0a;
  display: none;
  height: 200px;
  width: 200px;
}
form:focus-within + ul.ulclass, ul.ulclass:hover {
  display: block;
}
<form>
  <input type="text" value="Enter some text here" class="inputclass">
</form>
<ul class="ulclass">
  <a href="https://google.com">link</a>
</ul>

Upvotes: 5

Related Questions