bigskysoftware / bigskysoftware/htmx

Problem applying focus() after afterWap

Open
#3,411 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
49.4k
Forks
1.7k
Avg merge
3d 22h
Merged PRs (30d)
30

Description

I am using the following code combining thymeleaf and HTMX

I wrote a code to receive a serial number from an input form, and when the focus is removed from this input form, a request is sent to the server and the response is received as html based on thymleaf.

After the screen swap rendering is complete, I want to capture the htmx:afterSwap event in javascript and react based on the result.

If the serial number is empty or duplicated, we want to implement a user UX that gives **focus()** to the input tag so that the user can input again.

However, the focus is not assigned to the serial number and moves on to the next input tag. After entering the serial number, use the tab key or use the mouse to click the next input tag.

## Please tell me how to solve this problem.

I tried using various events, such as **html:afterSettle** and **html:afterSwap**, but I couldn't solve it.

## input form

```html


*
Serial Num







```

## Response HTML Code

```html



Please enter your serial number


⚠ This serial number has already been registered.


✔ Available serial numbers.


```

```js
document.body.addEventListener("htmx:afterSwap", function (evt) {
const targetId = evt.target.id;

if (targetId === "sn-check-result") {
const dataInvalid = evt.detail.target.querySelector("[data-invalid='true']");

if (dataInvalid) {
setTimeout(() => {
const inputSn = document.querySelector("#equipmentSn");
console.log("equipmentSn element:", inputSn);
console.log("is visible:", inputSn?.offsetParent !== null);
console.log("is enabled:", !inputSn?.disabled);

if (inputSn && inputSn.offsetParent !== null && !inputSn.disabled) {
inputSn.focus();
inputSn.select();
} else {
console.log("Focus failed - element not ready");
}
}, 100);
}
}
});
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.