Skip to content

add note about setting properties to JS.set_attribute/1 #3826

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions lib/phoenix_live_view/js.ex
Original file line number Diff line number Diff line change
Expand Up @@ -755,6 +755,34 @@ defmodule Phoenix.LiveView.JS do
show
</button>
```

> #### A note on properties {: .warning}
>
> `JS.set_attribute/1` cannot be used to set DOM properties such as the [`value` of an input](https://jakearchibald.com/2024/attributes-vs-properties/#value-on-input-fields).
> So if you find yourself wanting to do `JS.set_attribute({"value", "..."})` on an input, and
> see that updated value reflected in a form event, you should use `JS.dispatch/2`
> instead:
>
> Instead of
>
> ```heex
> <.button phx-click={JS.set_attribute({"value", ""}, to: "#my_input")}>...</.button>
> ```
>
> do
>
> ```heex
> <script :type={Phoenix.LiveView.ColocatedJS} name="clear_input">
> window.addEventListener("input:clear", (e) => {
> e.target.value = ""
> e.target.dispatchEvent(new Event("input", {bubbles: true}))
> })
> </script>
> <.button phx-click={JS.dispatch("input:clear", to: "#my_input")}>...</.button>
> ```
>
> Note: this uses `Phoenix.LiveView.ColocatedJS`, but you can also define the event listener directly inside
> your `app.js` instead.
"""
def set_attribute({attr, val}), do: set_attribute(%JS{}, {attr, val}, [])

Expand Down
Loading