Lately, I'm facing problems with HTML custom data attributes in my rails application. I user the following pattern in order to add some data attributes to the html tags and use them later in my javascript(jQuery) code:
= %a.name{ href: "url.com", data: {first_name: "ben", last_name: "amsalem} }
In the javascript code I access those attributes:
alert($(".name").data("first_name") + " " + $(".name").data("last_name"));
In my development environment it goes well and I get the expected result (the same is true for my production environment in the past), but in my current production version I get "undefined" values. I checked the HTML source of the page and I saw that I now have something like:
<a class="name" href="url.com" data-first-name="ben" data-last-name="amsalem" />
Instead of:
<a class="name" href="url.com" data-first_name="ben" data-last_name="amsalem" />
Why does it happen? What causes the change?
It's perfectly normal, data: { first_name: "ben" }
is supposed to produce data-first-name="ben"
.
The best way you would access this attribute is with .data("firstName")
, but .data("first-name")
would also work.
I take it that you are using HAML. Hypernation comes as default since 4.0. Set hyphenate_data_attrs
to false to turn this off.
Documentation: http://haml.info/docs/yardoc/Haml/Options.html#hyphenate_data_attrs-instance_method
Original github pull discussion: https://github.com/haml/haml/pull/488
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With