1

My goal is :

  • to show a popin when the user clicks on a button
  • to hide the popin when the user clicks elsewhere

I've tried this solution, and it works great : Use jQuery to hide a DIV when the user clicks outside of it

But I wanted to try something differently, I wanted to try focus()

So I made this code :

div
{
  width: 100px;
  height: 100px;
  border: 1px solid blue;
}

div:focus
{
  background-color: red;
}
<script>
function show()
{
 document.getElementById("element").focus();
}

</script>

<input type="button" onclick="show()" value="click me!"/>
<div id="element"tabindex="-1">

</div>
After you clicked the button, click elsewhere to remove the red background

And it works great, now I want to hide the block and show it when the user clicks the button, I just added display: block and display: none, that's the only difference between the two versions

div
{
  width: 100px;
  height: 100px;
  border: 1px solid blue;
  display: none;
}

div:focus
{
  background-color: red;
  display: block;
}
<script>
function show()
{
 document.getElementById("element").focus();
}

</script>

<input type="button" onclick="show()" value="click me!"/>
<div id="element"tabindex="-1">

</div>

And it's not working anymore, can someone tell me why?

Pascal Goldbach
  • 977
  • 1
  • 15
  • 34
  • If the div is the next sibling to the input, you could give the div a class such as `default-hidden` and write styles: `div.default-hidden { display: none }` and `input:focus + div.default-hidden { display: block }`. No need for the show function. – Kyle Richardson Nov 08 '17 at 21:11
  • Thank you @KyleRichardson, I didn't know that the `+` operator existed – Pascal Goldbach Nov 08 '17 at 21:20
  • 1
    It is a very useful selector. I wish there was a previous sibling selector. – Kyle Richardson Nov 08 '17 at 21:21

2 Answers2

5

You cannot focus an object that has display: none applied.

From this question:

Elements that are not visible cannot receive focus, therefore the :focus psuedo-class cannot apply.

John Ellmore
  • 2,209
  • 1
  • 10
  • 22
1

You can do this easily with CSS using the adjacent sibling selector. When the button is focused, the sibling div appears:

div {
  width: 100px;
  height: 100px;
  border: 1px solid blue;
  display: none;
}

button:focus + div {
  background-color: red;
  display: block;
}
<button type="button" value="">click me!</button>
<div id="element" tabindex="-1"></div>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209