fayong lin
fayong lin

Reputation: 224

making a picture slider in elm, model updates triggered by loaded element

I am making a website in elm that includes a dynamic element for browsing pictures. One can click a given thumb to see the full picture in a lightbox, navigate to the next or previous picture or let the picture change automatically every three second.

By default one sees only a small selection (4 thumbs) but it is possible to previews all the thumbs by clicking on "voir toute les photos"

running example here

Each user click or tick of the clock change the underlying model, which in turn makes the browser actualize the HTML accordingly.

I am mostly satisfied with the current level of functionality except for the fact than I can't find a way to display a transition screen (or picture) while the next picture is loading.

The lightbox displays the last displayed picture while loading the next one, and transitions abruptly.

Is there a way to trigger a change in the model only when the next picture is loaded?

Or a more idiomatic way to do this sort of thing? I am quite new to elm and web development in general.

the elm code for the gallery is visible at: https://github.com/eniac314/mairieMurol/blob/master/src/Gallery.elm

Upvotes: 4

Views: 844

Answers (1)

Chad Gilbert
Chad Gilbert

Reputation: 36375

It sounds like you just need a way to know when an image is finally loaded. You can tie into the img.onload DOM event, but first you'll need a Json Decoder to pull image src attribute out of an event.

Updated to elm-0.18

onLoadSrc : (String -> msg) -> Html.Attribute msg
onLoadSrc tagger =
    on "load" (JD.map tagger targetSrc)

targetSrc : JD.Decoder String
targetSrc =
    JD.at [ "target", "src" ] JD.string

Now you can use that decoder to call a new ImageLoaded String action, passing the image source as a string.

img
    [ src imgsrc
    , onLoadSrc ImageLoaded
    ]
    []

Look at demo and code (you may need to change the random number in the image url to combat the browser caching the image).

Upvotes: 5

Related Questions