Search code examples
javascripttwitter-bootstraptwitter-bootstrap-3sparklines

Javascript call on inactive Bootstrap tab content


I have a page with Bootstrap (v3) tabs:

https://getbootstrap.com/docs/3.3/javascript/#tabs

I have some Sparkline graphs rendered in each tab:

https://omnipotent.net/jquery.sparkline/#s-docs

and called like this:

  $('.sparkline-pie-remaining').sparkline('html', {
    type: 'pie',
    sliceColors: ['#1ab394', '#ed5565','#ddd'],
    width: '18',
    height: '18',
    offset: -90,
    disableTooltips: true,
    borderWidth: 1,
    borderColor: '#676a6c'
  });

The issue is that this does not get called on the inactive tabs. There is a callback which I tried for when the tab is shown but then it calls this each time the tabs change and the graphs are cleared out.

How do I get this call to happen on the inactive tab content when the page is rendered? Here is a CodePen to reproduce the issue:

https://codepen.io/dantappin/pen/rNegXOP


Solution

  • The reason why the Sparkline graph is not rendered inside the inactive tabs is because that tabpanel div has "display:none" attribute. Here's a section from the documentation you provided (see "Hidden Sparklines" section):

    If you try to display a sparkline in a tag that's currently not visible (ie. the tag or one of its parents are set to display:none) then you'll find that the sparkline hasn't been rendered when you finally do make the tag visible. This is because a tag with display:none has no size, and thus a canvas can't be created and sized for the sparkline to be rendered to.

    The solution is to call the $.sparkline_display_visible() function anytime a sparkline may have become visible so that it can be correctly rendered. This is the technique this site uses to handle the sparklines that are hidden in the different tabbed sections; the site calls the routine in the tab-changed callback.

    The solution is also included in the same quoted text. You can achieve this by attaching an event handler on either the tab button or the tabpanel div and by calling $.sparkline_display_visible() when the tab becomes active for the first time.

    EDIT: You can test this quickly by making the tab active and executing $.sparkline_display_visible() once in the JS console.