How to focus an element

Asked

Viewed 755 times

3

In CSS it would be something like this:

div {
    display: none;
}
div:active {
    display: block;
}

And some user action would give focus to this div by javascript

I know I can do adding and removing a class/attribute but I want to do without it

unsuccessfully:

document.getElementByTagName('div')[0].focus();

document.activeElement = document.getElementByTagName('div')[0];

1 answer

1


I think you’re mixing the pseudo-classes :active with :focus. The first occurs when you click and hold the click on the element; the second is when you receive Focus - these are different behaviors.

In this case you should use:

div:focus {
   display: block;
}

But that too would not work because it is not possible to give Focus to a hidden element.

Generally those that can receive Focus are form elements (inputs, selects etc.); divcan receive if you have the attribute tabindex, as shown in the example below:

document.querySelector("div").focus();
div {
   opacity: .2;
}
div:focus {
   opacity: 1;
}
Clique fora do texto para tirar o focus da div:
<br>
<div tabindex="1">texto</div>

In conclusion, his intention is not possible to realize, mainly with hidden elements.

Edit at author’s request

Since you can’t give the hidden element Focus, you can put opacity: 0 and position: absolute. So the element will be transparent and will not take up space in the layout:

document.querySelector("div").focus();
div {
   opacity: 0;
   position: absolute;
}
div:focus {
   opacity: 1;
   position: static;
}
Clique fora do texto para tirar o focus:
<br>
<div tabindex="1">texto</div> Texto texto

  • So it is not possible to focus on a hidden element? Even if it is with the opacity: 0 instead of display: none

  • This is not possible. Opacity does not cause the element to be hidden, it remains there, it just does not appear because it has no opacity.

  • With opacity is possible, because it is not hidden, as shown in the answer example.

  • Giving Focus to something that does not exist on the screen goes up against the concept of the function rs... How do I focus something that is not part of the layout? :)

  • So you can even do something like I want to... put the opacity: 0; position: absolute; in the element without the focus and with the focus put opacity: 1; position: initial;

  • put an example in the answer for me to accept

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.