Access function in app.js

Hi,

I try to do a rather simple js interaction but fail.

In my html (index.html.eex) I got
<button onclick="doClick()">Click me!<button>

and in my app.js I got the corresponding function
function doClick() { console.log('did it') }

But I get
ReferenceError: doClick is not defined

Do I explicitly make it available somehow?

The easiest way might be to define your function on window - window.onClick = function .... Not the best solution, but should do the job.

1 Like
<button id="myBtn">Click me!<button>
// somewhere in the top level of app.js
const btn = document.getElementById('myBtn');
btn.addEventListener('click', doClick, false);

MDN: EventTarget.addEventListener

Phoenix uses a bundler (Phoenix < 1.4 ? Brunch : webpack 4). This deliberately keeps everything out of the global space so the markup can’t find that function. Meanwhile JavaScript has no problem reaching into the DOM.

Modern JavaScript Explained For Dinosaurs

5 Likes

That article was legit the first useful JS post I’ve read in years. Finished it five days ago and most of what I didn’t understand was suddenly clear.

The ecosystem is still frustrating and dysfunctional – it’s JS after all – but at least it makes sense in its own way. And I now know what to reach for and when.

4 Likes

In the past 8 months I’ve spammed a link to that article 6 times (including this one).

3 Likes

Maybe put this one on your play queue: A Framework Author’s Case Against Frameworks

3 Likes

I’m sure it will. I was just a bit vauge as to what the question was. I got it to work the other way around but I wanted to find out why it did not work.

I expected something like this and there it is.

It does explain the huge jump from w3school’s Hello World to (virtualy) anything in production. Thank you.

1 Like