Last active
March 27, 2021 21:07
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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