How to get the browser screen size (width, height) in Phoenix LiveView

I need to know the browser window width and height in my LiveView app so I can adjust the output layout.
I could not find how to do it so far, after much googling.

Thanks for any help.
Gustavo

I’ve had a similar desire. It seems some layouts still require knowing browser width and height, especially on embedded or other small screens. Currently I’m just using a user option for say setting svg graph heights.

I’ve thought using a user hook on a client side element could work. It’d be clunky:

Somewhere add an empty element with a phx-hook:

<div id="info" phx-hook="ScreenInfo" />

Pseudo code:

let Hooks = {}
Hooks.ScreenInfo = {
  mounted() {
    this.pushEvent({ screenX: window..., screen: window... })
  }
}

let liveSocket = new LiveSocket("/live", Socket, {hooks: Hooks})

Not sure if there’s a browser event that fires on elements upon resizing, but if so that’d be a method to get events sent upon resizing.

1 Like

Would it be too difficult for LiveView to include the window.innerWidth and window.innerHeight into the:
params: %{
“altKey” => false,
“circle_id” => “b25e6a31-a55d-4a9d-988b-47ed8cad7151”,
“ctrlKey” => false,
“metaKey” => false,
“pageX” => 493,
“pageY” => 55,
“screenX” => 507,
“screenY” => 144,
“shiftKey” => false,
“value” => “”,
“x” => 493,
“y” => 55
},

???

It crossed my mind as well. I’m sure the LiveView devs would be willing to accept a PR… Alternatively if someone files a feature request it might get added.

Also how would it handle resize events?

On another note, another dev told me that CSS calc feature has landed in most browsers.

1 Like

Considering that on smartphones the width and height changes when you handle your phone in portrait or landscape mode, we should receive an event like this:

def handle_event(“window_size_changed”, params, %{assigns: assigns} = socket) do
…

In a PC browser, the event should be triggered whenever the user resizes the browser window.

not trying to re-open an old post, but if someone ends up here trying to figure out how to accomplish this, I did do something basically like this via a phx-hook described in this post:

There are three pieces to it:

  • div called page_resize
  • hook called PageResize
  • handle_event called page-resize

Now that alpinejs works with LiveView I think it would be possible to do with that as well, but I was unable to get the .window modifier to work with LiveView.

5 Likes