Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails and html data attributes: use dash(-) or underscore(_)?

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?

like image 580
benams Avatar asked Mar 05 '13 16:03

benams


2 Answers

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.

like image 157
Robin Avatar answered Oct 20 '22 05:10

Robin


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

like image 28
darshanags Avatar answered Oct 20 '22 05:10

darshanags