bigskysoftware / htmx

</> htmx - high power tools for HTML
https://htmx.org
Other
37.75k stars 1.28k forks source link

best way to trigger JS to focus an input text field that was newly swapped in #154

Closed ptrthomas closed 4 years ago

ptrthomas commented 4 years ago

this seems to be a common use case.

so I have a section of the page swapped with multiple elements that can include multiple <input> fields

but I want to focus only one of these fields, i.e. the cursor should be within a specified text field, and positioned after any text value that may be present

I'm finding it hard to figure out the best way to achieve this, I know afterSettle may be involved: https://htmx.org/events/#htmx:afterSettle

do suggest what you think would be the best / most elegant way to handle this

ptrthomas commented 4 years ago

I figured out one possible approach which may be a massive hack, but posting here in case it helps others and for feedback. I also feel a built-in way to "post process" some JS after a swap would be a nice addition to htmx

so in the HTML chunk returned, my server-side templating adds a <script> tag like this. this just needs to be added at the end of all the HTML, and it won't appear on the page

<script id="afterSettle">document.querySelector('#todo2').focus()</script>

and all that remains is to do an eval() on it. this event handler set up at the root page level does the trick:

      htmx.on("htmx:afterSettle", function (evt) {
        var el = document.getElementById('afterSettle');
        if (el) {
          Function('"use strict";' + el.innerHTML)();
        }
      });

do you think a built-in way to eval() pre-JS and post-JS sent similar to an out-of-band HTML snippet would be a feature request worth considering ?

benpate commented 4 years ago

I'd vote for eval()-ing any script tags in the swapped content. If performance is a consideration, then perhaps it could be put behind another tag, for example, hx-script="true"

I think this would be simpler than adding before/after logic, and less overhead than having to make another magic script id to be baked in to the library.

clarkevans commented 4 years ago

Lacking any experience with htmx, doing an eval of script tags seems like a simple solution. It has the nice advantage of keeping the code local to the widget that constructs the corresponding HTML. Would the Githubissues.

  • Githubissues is a development platform for aggregating issues.