Search code examples
elm

Elm using Html.attribute with "onmouseover" does not work


I would like to add onmouseover to change background color of Button. I do not need to use a Html.Events.onMouseOver since it is a very simple task. I do not want to use other external libraries.

I create Html.attribute with

div
[
   -- Html.Event.onMouserOver NoUse
   Html.attribute "onmouseover"  "$(this).css('background','green');"
]
[ ... ]

When I add unknown attributes to Elm. Elm addes "data-" prefix to the attributes Therefore, when I compile the code it will be translated to Html

<div data-onmouseover="$(this).css('background','green');">...</div>

So the "onmouseover" does not work!

How could I hack the "mouseover" event in Elm? and Why does Elm need to block such the event?


Solution

  • Elm does this intentionally to avoid script injection attacks (e.g: if you take a string from the user and give it as the value here, they can't write some malicious JS and have your page execute it).

    The correct solution to this is to use Html.Events.onMouseOver and Elm code (including, if you really need arbitrary JS, ports). You say you don't need to use it, but you do in Elm.

    Even if you could do what you wanted, it wouldn't actually work how you want: Elm controls the DOM for the page, and may destroy and recreate elements, meaning the changes you make in JS could be lost arbitrarily.