Error accessing dom nodes via js when both the js and html are in the payload
Consider a scenario like clicking on a link that returns a form with that uses select2. You need to init the select2 once the swap has happened. It would be nice to have the js that inits the select2 in the payload but right now you get an error like:
TypeError: Cannot read property 'querySelectorAll' of undefined
at J ([email protected]:1)
at $ ([email protected]:1)
at eval (eval at Re ([email protected]:1), <anonymous>:2:1)
at Re ([email protected]:1)
at He ([email protected]:1)
at [email protected]:1
at [email protected]:1
at R ([email protected]:1)
at i ([email protected]:1)
If you try and do that. Perhaps wait until after swap to execute js?
From the discord chat, this appears to be an issue only in the minimized code.
FYI I tried minifying the unminified version of htmx-0.2.0 manually and it works fine. Make me wonder if the minified build artifact in 0.20 isn't right. Maybe an older version got picked up?
Can you check if this is an issue w/ 3.0?
Sadly no although I get a different error now. It still works perfectly fine if I use the unminified code.
TypeError: $(...).ready is not a function
at eval (eval at ze (htmx.min.js:1), <anonymous>:2:13)
at ze (htmx.min.js:1)
at Ve (htmx.min.js:1)
at htmx.min.js:1
at htmx.min.js:1
at N (htmx.min.js:1)
at i (htmx.min.js:1)
Ye @ htmx.min.js:1
ze @ htmx.min.js:1
Ve @ htmx.min.js:1
(anonymous) @ htmx.min.js:1
(anonymous) @ htmx.min.js:1
N @ htmx.min.js:1
i @ htmx.min.js:1
setTimeout (async)
e @ htmx.min.js:1
Ht.h.onload @ htmx.min.js:1
load (async)
Ht @ htmx.min.js:1
t @ htmx.min.js:1
Here's the js that is on the page that is being sent down in the GET...
<script type="text/javascript">
$(document).ready(function() {
$('#id_user').select2({
ajax: {
url: '/app/appaccounts/app-user-autocomplete-no-create/',
dataType: 'json'
}
});
$("#cancel").click(function () {
closeUserPicker();
});
$(document).on('click', function (e) {
if ($(e.target).closest("#plus-one-dialog").length === 0) {
closeUserPicker();
}
});
function closeUserPicker() {
$("#plus-one-dialog").remove();
}
});
</script>
Ah... another interesting tidbit. If I change the code above to use jQuery instead of $ e.g. jQuery('#id_user') vs. $('#id_user') the error goes away and everything works fine. Perhaps something in how minimization maps symbols or in whether or not $ is mapped when eval is used?
hmmm
the eval is being done in the context of the htmx internals, so if the minifier is generating something with the $ character, that might be the issue...
Maybe I should move the eval function outside of the htmx core so it has a cleaner evaluation scope...
@bencroker found a great article which pointed to this:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function
which should eliminate this janky name space collision