javascriptattributesdatasetparallaxskrollr

Javascript dataset with numbered names conundrum


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?


Solution

  • Try

    var elem = document.createElement('div');
    elem.setAttribute("data-0", "foo");