Focusing on an element

3

In CSS it would look something like this:

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

And some user action would focus on this div by javascript

I know what I can do by adding and removing a class / attribute however I want to do without it

I tried, unsuccessfully:

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

document.activeElement = document.getElementByTagName('div')[0];
    
asked by anonymous 28.05.2018 / 00:36

1 answer

1

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

In this case you should use:

div:focus {
   display: block;
}

But that too would not work because you can not focus on a hidden element.

Generally those that can receive focus are elements of forms (inputs, selects etc.); :active s can receive if they have the :focus attribute, 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, your intent is not possible to accomplish, especially with hidden elements.

Edit at the request of the author

Because you can not focus on the hidden element, you can put div and tabindex . 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
    
28.05.2018 / 01:17