Gilou06
Infer user click position in img using LiveView
Hello,
I’m struggling to code a LiveView that will return the exact position user clicks into an img HTML element.
My issue is about getting the element DOM naturalwidth and naturalheight.
Even though I set the img width to say 600px, for some reasons I don’t know, in some pages the image is actually displayed as 681px width.
So, when I retrieve the user click offsetX position (from the on-click event), it varies from 0 to 681 range and not from 0 to 600 range as expected.
That throws my computation off since I base it on 600, not 681 !
I think I could solve the issue by querying the clicked element about its naturalwidth, but I don’t know how to do that. I bet Javascript hook is the right path, but can’t work my head around it.
Any tips are welcome.
My current app.js liveSocket code is
let liveSocket = new LiveSocket("/live", Socket, {
hooks: Hooks, params: { _csrf_token: csrfToken }, metadata: {
click: (e, _el) => {
return {
offsetX: e.offsetX, offsetY: e.offsetY, clientX: e.clientX,
clientY: e.clientY, pageX: e.pageX, pageY: e.pageY
}
}
}
})
Thank you
Jean-yves ![]()
Marked As Solved
codeanpeace
_el has clientWidth and clientHeight properties that may be what you’re looking for.
click: (e, el) => {
return {
offsetX: e.offsetX,
offsetY: e.offsetY,
clientWidth: el.clientWidth,
clientHeight: el.clientHeight
}
}
Also Liked
Gilou06
Hi, it worked perfectly, thank you !
If I try to understand from your answer I get this : e is about the event and el about the HTML element.
Is this standard to the HTML/Javascript world to have those two data element linked to the click event ? (I could not find relevant Javascript documentation about that).
Anyway, thanks to you I can pursue and will be able to use all events and elements related properties in the future.
A big thank you from France.
Jean-yves ![]()
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








