Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elm: Get window-width on load

Tags:

css

frontend

elm

So I am doing a pretty basic landing page in Elm and I want to determine what picture to use depending on the initial screen size and then again on resize. I found the resize function on the Window module, and made it work fine, but I couldn't figure out how to do it on load as well.

I am looking for something like:

initialModel : Model
initalModel model =
    {width = Window.size.width}

I have ended up making the picture as background-image on a div and then changing the picture depending on screen size, but it just feels less than ideal. Is the next best way to use elm-css? Am I missing something obvious?

like image 475
Mathias Egekvist Avatar asked Mar 04 '18 21:03

Mathias Egekvist


1 Answers

To obtain a value at app load time, you will probably want to use Html.programWithFlags and pass the window size in from Javascript.

type alias Flags =
    { windowWidth : Int }

type alias Model =
    { windowWidth : Int, ... }

main =
    Html.programWithFlags
        { init = init
        , update = update
        , subscriptions = \_ -> Sub.none
        , view = view
        }

init : Flags -> ( Model, Cmd Msg )
init flags =
    { windowWidth = flags.windowWidth } ! []

You pass in flags on app startup like so:

var app = Elm.Main.fullscreen({ windowWidth: window.innerWidth })
like image 88
Chad Gilbert Avatar answered Nov 02 '22 22:11

Chad Gilbert