7stud

7stud

How do I use JQuery in a Phoenix app?

What do I have to do to use JQuery in a Phoenix app? Suppose I create my Phoenix app like this:

/phoenix_apps% mix new --umbrella a_umbrella
* creating README.md
* creating .formatter.exs
* creating .gitignore
* creating mix.exs
* creating apps
* creating config
* creating config/config.exs

Your umbrella project was created successfully.
Inside your project, you will find an apps/ directory
where you can create and host many apps:

    cd a_umbrella
    cd apps
    mix new my_app

Commands like "mix compile" and "mix test" when executed
in the umbrella project root will automatically run
for each application in the apps/ directory.


~/phoenix_apps% cd a_umbrella/apps
~/phoenix_apps/a_umbrella/apps% mix new my_app --sup
* creating README.md
* creating .formatter.exs
* creating .gitignore
* creating mix.exs
* creating lib
* creating lib/my_app.ex
* creating lib/my_app/application.ex
* creating test
* creating test/test_helper.exs
* creating test/my_app_test.exs

Your Mix project was created successfully.
You can use "mix" to compile it, test it, and more:

    cd my_app
    mix test

Run "mix help" for more commands.

That gives me this directory structure:

~/phoenix_apps/a_umbrella% tree .
~/phoenix_apps/a_umbrella% tree .
.
├── README.md
├── apps
│   └── my_app
│       ├── README.md
│       ├── lib
│       │   ├── my_app
│       │   │   └── application.ex
│       │   └── my_app.ex
│       ├── mix.exs
│       └── test
│           ├── my_app_test.exs
│           └── test_helper.exs
├── config
│   └── config.exs
└── mix.exs

6 directories, 9 files

What do I need to do to use JQuery in a template?

Marked As Solved

03juan

03juan

This will import hello into the scope of app.js, but will not make it available to the HTML document automatically unless you assign the function to the global window element.

// file: assets/js/app.js
import {hello} from "../vendor/my_functions.js" 
window.hello = hello

A good next step would be to namespace your exported functions, then assign that to the global element:

// file: assets/vendor/my_functions.js
export function hello () {...}
export function etc () {...}

// file: assets/js/app.js
import * as MyFunctions from "../vendor/my_functions.js" 
window.MyFunctions = MyFunctions

// in HTML <script>
window.onload = function () {
  MyFunctions.hello()
  MyFunctions.etc()
}

This can start to get unwieldy when you have a lot of functionality in multiple HTML scripts.

I would instead move them to app.js and set up your code from there:

// file: assets/js/app.js
import * as MyFunctions from "../vendor/my_functions.js" 

window.onload = function () {
    MyFunctions.hello()
}

// now this is only necessary if you also want to access them directly from the dev console
window.MyFunctions = MyFunctions

Lastly, if app.js also gets too large for your liking, or you only want to have certain features running in specific pages, you can move the relevant code to its own module, have esbuild compile it separately, then load it into your page.

// file: assets/js/my_feature.js
import { hello } from  "../vendor/my_functions.js" 

button = document.querySelector("#someButton")
button.addEventListener("click", () => { hello() }

add js/my_feature.js to the esbuild args string (and restart the server to apply changes to config files)

# file: config/config.exs
config :esbuild,
  version: "0.17.11",
  default: [
    args:
      ~w(js/app.js js/my_feature.js --bundle --target=es2017 --outdir=../priv/static/assets --external:/fonts/* --external:/images/*),
    cd: Path.expand("../assets", __DIR__),
    env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)}
  ]
<!--- my_page.html.heex or inside render/function component ~H template -->
<script defer phx-track-static type="text/javascript" src={~p"/assets/my_feature.js"}>
</script>

<button id="someButton" type="button">Run hello()</button>

Also Liked

odix67

odix67

First, do you really need an umbrella app ?
Second, you just generate a template for an umbrella app, please follow the steps in Overview — Phoenix v1.8.8, how to create a phoenix app and how to integrate third party JS libs

Exadra37

Exadra37

What is the use case for JQuery?

odix67

odix67

If you don’t know if you need an umbrella application, I would propose you do not need one. Just start with a simple phoenix application using mix phx.new
I’ve the book too, besides others, a lot others ;-), but I’ve not read it through, especially not that mentioned part.
Personally, I would recommend reading “Elixir in Action” by Sasa Juric, then you may read “Phoenix in Action” to understand the basics of phoenix or go directly to “Programming Phoenix LiveView” by Bruce A. Tate and Sophie DeBenedetto.
The you may decide if you really need JQuery.
If you are an online learning guy, I would recommend the Elixir/OTP and Phoenix LiveView courses from ProgamticStudio and Grox.io Learning

Where Next?

Popular in Questions Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
mgjohns61585
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
nobody
How to bind a phoenix app to a specific ip address? could not find anything about that, nowhere, unfortunately, but for me this is quite...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New

Other popular topics Top

sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 42920 311
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a &gt; b) do {:ok, "a"} end if (a &lt; b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
Qqwy
Update: How to use the Blogs &amp; Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 126479 1222
New

We're in Beta

About us Mission Statement