Skip to content

Instantly share code, notes, and snippets.

@henrik
Last active March 27, 2021 21:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save henrik/6f62c862b47407d78ac3b9b430835557 to your computer and use it in GitHub Desktop.
Save henrik/6f62c862b47407d78ac3b9b430835557 to your computer and use it in GitHub Desktop.
Phoenix LiveView hook that makes links with a "phx-click" still trigger the default navigation event, and also prevents clicks on buttons inside these links from doing the same.
// Fixes two issues:
// - Clicking a link with a `phx-click` attribute did not cause the link default (navigation) to trigger.
// - Clicking a button inside the link *would* cause the link default to trigger.
Hooks.AllowLinkDefaultAndPreventNestedDefault = {
mounted() {
this.el.addEventListener("click", (e) => {
// `closest` in case we click an element inside a button, e.g. an icon.
if (e.target.closest("button")) {
e.preventDefault()
} else {
location.href = this.el.href
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment