0

I'm using the Skrollr.js library to do some parallax scrolling on a page. The library uses datasets to specify some start and finish css code (based on your scroll position) example:

<div data-0="top:0px;" data-100="top:500px"></div>

I need to dynamically create a few elements and set their datasets, which say, for example, if the element looked like this:

<div data-foo="bar"></div>

This would work fine:

var elem = document.createElement('div');
    elem.dataset['foo'] = 'bar';

But because I'm using the library which uses integers for names ( data-0 ), I'm stuck... I've tried this:

   elem.dataset[0] = 'foo';

and...

   elem.dataset['0'] = 'foo';

no luck... any other ideas?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Nick Briz
  • 1,917
  • 3
  • 20
  • 34

1 Answers1

1

Try

var elem = document.createElement('div');
elem.setAttribute("data-0", "foo");
jefftimesten
  • 366
  • 6
  • 13
  • It's important to note the reason why this works. jefftimesten is treating the data-0 attribute as an arbitrary attribute. This is safe in all browsers. @Nick you are treating it as a property of the element's dataset, which is an HTML5 concept and is only safe in modern browsers. In addition to that, the naming of a data attribute has to follow specific rules. One of which is it can't start with a number. So in all honesty, the Skrollr library should be updated to be compliant (data-0 to data-p0 maybe). Read more here: https://developer.mozilla.org/en-US/docs/DOM/element.dataset – DingoEatingFuzz Jan 19 '13 at 23:08
  • OF COURSE! Thnx jeffimesten, I thought I had tried that... alas I had not, I feel silly :) and Thnx DingoEatingFuzz, mayhaps I'll post an issue on the library's github – Nick Briz Jan 19 '13 at 23:14