JQuery – Sparkline: Re-draw on resize / responsive sparklines

I’ve been suckered in by the awesome JQuery Sparkline plugin – I won’t go over how it works or what it does, but rather a quick ‘fix’ for fixing issues with how the output deals with browser resizing. (Long story short, it doesn’t by default).

Here’s a visual of the issue I’m talking about with responsive/resizing layouts

 

Normal:

After resize:

 

The fix:

Assign your Sparkline initialization to a variable as a function.

Then call the function to intialize, and bind it to JQuery’s $.resize() method.

I also used a short setTimeout() to avoid excessive redrawing during the resize operation.

And voila!

 

4 thoughts on “JQuery – Sparkline: Re-draw on resize / responsive sparklines

  1. Your usage of setTimeout is not stopping the excessive redraw of sparklines, just delays it.

    You need to use clearTimeout as well:


    $(function() {

    var sparklineLogin = function() {
    $('#adv-login-sparkline').sparkline(
    [ pointData ],
    {
    type: 'line',
    width: '100%',
    height: '25'
    }
    );
    }

    var refreshSparklines;
    $(window).resize(function(e) {
    clearTimeout(refreshSparklines);
    refreshSparklines = setTimeout(sparklineLogin, 500);
    });
    sparklineLogin();
    });

    1. styu: You’re absolutely right – good catch.I had dealt with that issue in my project and never updated the post.

      I’ve updated the example; thanks for the feedback.

Leave a Reply

Your email address will not be published. Required fields are marked *