Sibert
(Sibert)
1
If I use jsfiddle this works as it should:
const btns = document.querySelectorAll(".btn");
const nav = document.querySelector(".nav");
https://jsfiddle.net/0x54fL7t/10/
Using Javascript in Go it does querySelectorAll() work…
But not querySelector
Why does exact the same code work outside Go, but not using Go?
Any tip what I am doing wrong?
lutzhorn
(Lutz Horn)
2
What do you mean by that? How do you execute JavaScript “using Go”?
Sibert
(Sibert)
3
In main:
func init() {
tpl = template.Must(template.ParseGlob("public/templates/*.html"))
http.Handle("/js/", http.StripPrefix("/js/", http.FileServer(http.Dir("./public/js"))))
}
In httphead:
<head>
<script type="text/javascript" src="/js/nav.js"></script >
</head>
In main template:
<div class="nav">
{{template "nav" ("faq")}}
</div>
In nav.js
const btns = document.querySelectorAll(".btn");
const nav = document.querySelector(".nav");
alert(nav)
alert(btns)
So the Javascript is called by the head inside a template.
The strange thing is at that:
document.querySelectorAll(".btn") ...works
document.querySelector(".nav"); ...fails
The only difference is that .btn is in a sub template. Both works outside Go.
Sibert
(Sibert)
4
I found the cause.
<head>
<script src="/js/nav.js" defer></script >
</head>
It turned out that the Javascript was loaded before the page was loded. By adding defer it worked.
system
(system)
Closed
5
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.