1

I am looking for a way to call client side JavaScript code from within Elixir .leex files without needing to install Node.js

My goal is to convert html to an image bitstring with something like this library: http://html2canvas.hertzen.com/

I have also looked at https://github.com/revelrylabs/elixir-nodejs as an example.

2
  • I suggest you to add more tags Commented Oct 18, 2021 at 20:58
  • Where do you want the JavaScript code to run? You say "client side" (i.e. JavaScript code that runs in the client browser) but then you mention Node.js which would be useful for running JavaScript code on the server. Where do you want the code to run? Commented Oct 19, 2021 at 4:22

1 Answer 1

1

In a .*eex file you can inject javascript into your elements as a string and it should work. For simple js I do this in my own heex sigils in .ex files. For example,

<button onclick="(() => document.documentElement.scrollTop = 0)()">
  Scroll to top
</button>

If your html2canvas function is defined in the javascript bundle delivered to the client, then triggering the function you wrote as a string in your .*eex file should work.

In my opinion this shouldn't really be done for non-trivial js. If you are using Phoenix LiveView, look into hooks. You would write your custom js and trigger it off of a hook, or use a hook to push an event that you would handle server-side in Elixir.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.