jqueryflotzepto

Combine Flot with Zepto


Is one able to use Zepto with Flot and how?

I know Flot works fine with jQuery (tested), but Zepto just feels faster and smoother, than jQuery on mobile devices


Solution

  • I tried it and ran into two problems. First, flot looks for jQuery to be defined and second, flot uses outerWidth which zepto doesn't replicate.

    So, let's give it a little love and work around these problems:

    <!DOCTYPE html>
    <html>
    
    <head>
      <script>
      </script>
      <!-- Load Zepto -->
      <script data-require="zepto@1.1.4" data-semver="1.1.4" src="https://cdnjs.cloudflare.com/ajax/libs/zepto/1.1.4/zepto.min.js"></script>
      <!-- patch in the things we need -->
      <script>
         // define jquery
        jQuery = $;
        // create outerWidth/Height functions
        // stolen from here: https://gist.github.com/pamelafox/1379704
        ['width', 'height'].forEach(function(dimension) {
          var offset, Dimension = dimension.replace(/./, function(m) {
            return m[0].toUpperCase()
          });
          $.fn['outer' + Dimension] = function(margin) {
            var elem = this;
            if (elem) {
              var size = elem[dimension]();
              var sides = {
                'width': ['left', 'right'],
                'height': ['top', 'bottom']
              };
              sides[dimension].forEach(function(side) {
                if (margin) size += parseInt(elem.css('margin-' + side), 10);
              });
              return size;
            } else {
              return null;
            }
          };
        });
      </script>
      <!-- now we can include flot -->
      <script data-require="flot@0.8.2" data-semver="0.8.2" src="//cdnjs.cloudflare.com/ajax/libs/flot/0.8.2/jquery.flot.min.js"></script>
    </head>
    
    <body>
      <div id="placeholder" style="width:300px;height:300px"></div>
      <script>
        $(function() {
    
          var d1 = [];
          for (var i = 0; i < 14; i += 0.5) {
            d1.push([i, Math.sin(i)]);
          }
    
          var d2 = [
            [0, 3],
            [4, 8],
            [8, 5],
            [9, 13]
          ];
    
          // A null signifies separate line segments
          var d3 = [
            [0, 12],
            [7, 12], null, [7, 2.5],
            [12, 2.5]
          ];
    
          $.plot("#placeholder", [d1, d2, d3]);
        });
      </script>
    </body>
    
    </html>