Using data-attributes to set string and JSON objects in Bootstrap

Using data-attributes to set string and JSON objects in Bootstrap

Last updated:

When using bootstrap widgets, like tooltips, for example, you have two ways to set options for the widget:

  • send parameters to the triggering method:

    $('#example').tooltip(options);
    

    where options is a javascript object: (JSON notation)

    $('#example').tooltip({
            html:true,
            trigger:'hover'
    });
    
  • data-attributes: any attributes that are configurable via the javascript method can also be declared directly in the HTML elements as data-attributes.

HTML code:

    <input type="text" data-delay="100" class="tt"/>

or

    <div class="tt" data-placement="right">
    //some stuff
    </div>

and some JS:

    $(".tt").tooltip({
        html:true
    });//you can still set stuff here

note that any attribute set via data-attributes override any other you have set via the javascript trigger method.

  • JSON-like data-attributes: Now, what happens if you want to set non-trivial (i.e. composite JSON objects) tooltip options via data-attributes?

The answer that is you can't. Not with the normal version of bootstrap. I've searched on the web a little bit and found out that some smart people have already figured out how to modify bootstrap in order to allow you to set data-attributes for stuff like this as data-attributes:

    options:{
        delay:{
            show:800,
            hide:100
        }
    }

You just need to modify bootstrap.js like it's shown on this github commit and then you can start doing things like this:

    <div data-delay-hide="100" data-delay-show="1000">
    //some content
    </div>

to set tooltip options via data-attributes. Of course, you can also generalize this solution for all widgets that require composite attributes like this one.

Dialogue & Discussion