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!

 

5 Comments
  1. Bill says:

    Thanks – just what I was looking for!

    Reply
  2. styu says:

    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();
    });

    Reply
    • 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.

  3. Amy says:

    Thank you so much! Just saved me a bunch of time figuring this out!

    Reply
  4. Actually a simpler solution is to refer to the canvas within the sparkline and resize it to 100% on the event:

    $(window).resize(function(e) {
    $(‘.adv-login-sparkline canvas’).css(“width”,”100%”);
    });

    Specially if you are using the text in the html, otherwise when you redraw it won’t have any values for the sparkline

    Reply
Leave a Reply




XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">