DEV Community

Cover image for Focus does not follow click()
Michal Bryxí
Michal Bryxí

Posted on

Focus does not follow click()

When you click around on a webpage the currently focused element changes accordingly. If you want to see which DOM element is focused now, you can simply click on some element, open dev tools and execute:

document.activeElement

> <textarea class="articleform__body" id="article_body_markdown" placeholder="Body Markdown" name="body_markdown" style="height: 714px;"></textarea>
Enter fullscreen mode Exit fullscreen mode

I assumed the same for JavaScript click() call. But after way too long of desperate code debugging I found out that:

focus does not follow click()

So if you try to run following code in your JS console directly here on dev.to:

document.querySelector("#nav-search").click();
console.log("Active element:", document.activeElement);

> Active element: <textarea class="articleform__body" id="article_body_markdown" placeholder="Body Markdown" name="body_markdown" style="height: 798px;"></textarea>
Enter fullscreen mode Exit fullscreen mode

Active element won't be the click-ed search bar. For that you would have to run:

document.querySelector("#nav-search").focus();
console.log("Active element:", document.activeElement);

> Active element: <input class="nav-search-form__input" type="text" name="q" id="nav-search" placeholder="search" autocomplete="off" aria-label="search">
Enter fullscreen mode Exit fullscreen mode

You can play with a more complete demo including how focusout() fits in the equation.

Lesson learned.


Cover photo from Free-Photos on pixabay

Top comments (0)