Skip to content

Instantly share code, notes, and snippets.

@henrik
Last active Mar 27, 2021
Embed
What would you like to do?
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