Closed ptrthomas closed 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 ?
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.
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.
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>
fieldsbut 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:afterSettledo suggest what you think would be the best / most elegant way to handle this