2012-03-22

HTML5 DOM Control with WebSharper

w3schools.com > HTML5 Tutorial > HTML5 Video/DOM shows how to manipulate a <video> of a bunny via onclick events of <button> elements. Here I produce the same layout and behavior using WebSharper. Some benefits are that you get reusable components, type safety, and minimized JavaScript when in Release mode.

[<JavaScript>]
let videoJs() : IPagelet =
   
    // HTML DOM Layout (via JavaScript)

    let playPause = Button [Text "Play/Pause"]
    let makeBig = Button [Text "Big"]
    let makeSmall = Button [Text "Small"]
    let makeNormal = Button [Text "Normal"]

    let id = "video1"

    let videoEl =
        Video [Id id; Width "420"]
        -<
        [
        Source [Src "http://www.w3schools.com/html5/mov_bbb.mp4"; Type "video/mp4"]
        Source [Src "http://www.w3schools.com/html5/mov_bbb.ogg"; Type "video/ogg"]
        ]
        -< [Text "Your browser does not support HTML5 video."]
   
    let div = Div [Attr.Style "text-align:center"] -< [playPause; makeBig; makeSmall; makeNormal; Br[]; videoEl]

    // JavaScript Behavior

    let video() = As<HTMLVideoElement>(ById id)

    playPause |> OnClick (fun _ _ ->
        let v = video()
        if v.Paused then v.Play() else v.Pause()
    )

    makeBig |> OnClick (fun _ _ -> video().Width <- "560")
    makeSmall |> OnClick (fun _ _ -> video().Width <- "320")
    makeNormal |> OnClick (fun _ _ -> video().Width <- "420")

    div :> IPagelet

The full source for VideoBunny.fs and the solution are available. I created it with WebSharper 2.4 and Visual Studio 11 Beta, but it works with VS 10 as well. Feedback is welcome, especially if you know WebSharper better.