JavaScript on page

Hello,

I’m creating a complex website and I’m using in general jQuery. On some pages (markdown files) I would like to add a document.ready function . How can I put some JavaScript code inside the markdown file?
My first idea is to create a page property, which is put inside the header if it is set. But is there any buildin functionality to put page specialized JavaScript code to a page?

Thx

@flashpixx

https://discuss.gohugo.io/t/javascript-in-blogpost-but-not-on-all-sites-at-the-same-time/3978/7

Thanks for that, but I understand it in this case, that I can define a JavaScript file and include it by a block structure, but in my case I would like to add “inline JavaScript code”.

You can include regular HTML in you Markdown files. So a <script> tag should work. Maybe it can happen that Go templates escape them for security reasons (unless Hugo trusts the user and marks it as safe by default).

1 Like

@flashpixx

https://gohugo.io/templates/functions#safejs

Yes the problem are the quotes. I have got this code e.g.

<script>
$(document).ready(function() {
     $("#animatefsm").click( {
	console.log("foo");
 } );
}
</script>

And the double-quotes within the jQuery call are escaped. How can I avoid the escaping within the markdown file of this block?

Thanks

1 Like

… just an idea, … not sure/didn’t try - about that :

{{ `<script>
$(document).ready(function() {
$("#animatefsm").click( {
console.log(“foo”);
} );
}
</script>` | safeJS }}

note: use backticks not apostrophes

The answer proposed on this page by snapo is to move all the javascript to one line in between the <script> and </script> tags.

That works for me in Hugo 56.3

2 Likes

Correct me if I’m wrong but if you put in your config.toml

[markup]
  [markup.goldmark]
    [markup.goldmark.renderer]
      unsafe = true

then something like

<script>

console.log('Hello World');

</script>

works in your markdown file without problems.