Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <link href="https://api.tiles.mapbox.com/mapbox.js/v2.1.4/mapbox.css" rel="stylesheet" />
</head>

<body>
  <div class="outter-wrap">
    <div id="container">
      <div class="button">
        <button id="reset">Reset</button>
      </div>
      <div id="d3Map"></div>
      <div id="mbMap"></div>
    </div>

    <div id="bottom-container">
      <div class="legend-container">
        <div class="legend-bar-color">
          <div class="color color0"></div>&#62;&nbsp;0.9&#37;</div>
        <div class="legend-bar-color">
          <div class="color color1"></div>&#62;&nbsp;2.7&#37;</div>
        <div class="legend-bar-color">
          <div class="color color2"></div>&#62;&nbsp;4.5&#37;</div>
        <div class="legend-bar-color">
          <div class="color color3"> </div>&#62;&nbsp;6.3&#37;</div>
        <div class="legend-bar-color">
          <div class="color color4"></div>&#62;&nbsp;8.1&#37;</div>
      </div>

      <div class="footer-wrap">
        <p>Source: Bureau of Labor Statistics, 2013</p>
      </div>
    </div>
  </div>
  <!-- EXTERNAL JS FILES -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
  </script>
  <script src="https://api.tiles.mapbox.com/mapbox.js/v2.1.4/mapbox.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8">
  </script>
  <script src="https://d3js.org/topojson.v1.min.js">
  </script>
</body>
              
            
!

CSS

              
                body, html {
  width: 100%;
  margin: 0; }

.outter-wrap {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
  padding: 20px;
  box-sizing: border-box; }

#container {
  position: relative;
  width: 100%;
  padding-bottom: 59%; }

#mbMap {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 60px;
  left: 0; }

#d3Map {
  position: absolute;
  width: 100%;
  height: 100%;
  /* quantile color scale */ }
  #d3Map .counties {
    fill: #c6c6c6;
    cursor: pointer; }
  #d3Map .q0-5 {
    fill: #dbd9eb; }
  #d3Map .q1-5 {
    fill: #cbc9e2; }
  #d3Map .q2-5 {
    fill: #9e9ac8; }
  #d3Map .q3-5 {
    fill: #756bb1; }
  #d3Map .q4-5 {
    fill: #54278f; }
  #d3Map .state-borders {
    fill: none;
    stroke: #fff;
    stroke-width: 1.5px;
    stroke-linejoin: round;
    stroke-linecap: round;
    pointer-events: none; }

/* RESET BUTTON */
button {
  padding: 10px 10px 10px 10px;
  background-color: white;
  color: #636363;
  box-shadow: 0 1.5px 0 #e2e2e2;
  border-radius: 3px;
  -moz-border-radius: 3px;
  border: 1.5px solid #c2c2c2;
  font-family: 'Arial';
  text-transform: uppercase;
  font-weight: bold;
  font-size: 12px;
  text-align: center;
  cursor: pointer; }

button:hover {
  background-color: #ededed; }

/* on selection */
button:focus {
  /* remove shadow & blue outline */
  outline: 0;
  background-color: gray;
  color: #fff; }

/* on button press */
button:active {
  box-shadow: none;
  background-color: #ededed;
  color: #636363; }

/* LEGEND STYLES */
#bottom-container {
  position: relative; }

.legend-container {
  position: relative;
  width: 100%;
  text-align: center; }
  .legend-container .legend-bar-color {
    display: inline-block;
    position: relative;
    width: 14.5%;
    text-align: center;
    font: 13px 'Helvetica Neue', Helvetica, arial, sans-serif;
    color: #5a5a5a; }
  .legend-container .color {
    width: 95%;
    height: 18px; }
  .legend-container .color0 {
    background-color: #dbd9eb; }
  .legend-container .color1 {
    background-color: #cbc9e2; }
  .legend-container .color2 {
    background-color: #9e9ac8; }
  .legend-container .color3 {
    background-color: #756bb1; }
  .legend-container .color4 {
    background-color: #54278f; }

.detail {
  top: 80px; }

/* FOOTER STYLES */
.footer-wrap {
  position: relative;
  width: 100%;
  text-align: center;
  color: #626764;
  font: 11px 'Helvetica Neue', Helvetica, arial, sans-serif; }
              
            
!

JS

              
                'use strict';

//jquery global variables
var $mbMap = $('#mbMap').attr('style', 'visibility: hidden;');
var $reset = $('button[id=reset]').hide();
var $d3Map = $('#d3Map');
var $bottom = $('#bottom-container');

// initialize mapbox map (outside logic to avoid duplicate initializations).
L.mapbox.accessToken = 'pk.eyJ1Ijoic3ByaW5nZmllbGQiLCJhIjoiMmZkYmQ2MDIwMzc0NzU2NGJlNjY3YWFhZTdkOTIzNDMifQ.p8t3Dhdb5i6yAef33jU3LQ';
var mbMap = L.mapbox.map('mbMap', 'mapbox.streets', {
  minZoom: 4,
  maxZoom: 10
});

// array for our state geojson featureLayer
var overlayLayers = [];

// d3 map parameters
var width = $d3Map.width();
var height = $d3Map.height();

var quantize = d3.scale.quantize()
    .domain([0.9, 9.9])
    .range(d3.range(5).map(function(i) { return 'q' + i + '-5'; }));

var projection = d3.geo.albersUsa()
    .scale(width / 0.285 / Math.PI)
    .translate([width / 2, height / 2]);

var path = d3.geo.path()
    .projection(projection);

var svg = d3.select('#d3Map').append('svg')
    .attr('width', width)
    .attr('height', height);

var g = svg.append('g')
    .attr('class', 'county-container');

// render maps
var countyBounds = [];

d3.json ('https://raw.githubusercontent.com/sfrostenson/d3-mapbox-template/master/bin/counties.json', function (error, us) {
  if (error) { return console.error(error); }

  countyBounds = topojson.feature(us, us.objects.counties).features;

  var counties = g.append('g')
        .attr('class', 'counties')
      .selectAll('path')
        .data(countyBounds)
      .enter().append('path')
        .attr('class', function (d) { return quantize(d.properties.r); })
        .attr('d', path)
        .on('mouseover', function (d) {
          d3.select(this)
          .style('stroke', '#fff')
          .style('stroke-width', '2.5px');
        })
        .on('mouseout', function (d) {
          d3.select(this)
          .style('stroke', 'none');
        })
        .on('click', clicked);

  var borders = g.append('path')
      .datum(topojson.mesh(us, us.objects.counties, function (a, b) { return a.id / 1000 ^ b.id /1000; }))
      .attr('class', 'state-borders')
      .attr('d', path);

  // D3 map resize function
  var onResize = function() {
      var width = $d3Map.width();
      var height = $d3Map.height();

      svg.attr('width', width)
        .attr('height', height);

      projection.scale(width / 0.285 / Math.PI)
        .translate([width / 2, height / 2]);

      path.projection(projection);
      counties.attr('d', path);
      borders.attr('d', path);
  };

  $(window).resize(debounce(onResize, 200, false));

  var usLayer = L.geoJson(countyBounds, { style: style }).addTo(mbMap);
  
});

// transition from d3 view to mapbox view on click
function clicked(d) {
  $d3Map.fadeOut(600);
  $mbMap.fadeIn(1000);
  var centroid = path.centroid(d);
  var x = centroid[0];
  var y = centroid[1];
  var zoom = 1;
  $reset.show();
  $mbMap.attr('style', 'visibility: visible;');
  $bottom.addClass('detail');

  var stateBounds = getBounds(getState(d.properties.s));
  overlayLayers.push(stateBounds);
  
  // hardcode AK
  if (d.properties.s === 'AK') {
      mbMap.fitBounds([[54.113578, -165.835171], [70.568625, -142.547859]]);
    } else {
      mbMap.fitBounds(stateBounds.getBounds());
    }

  g.transition()
      .duration(750)
      .attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')scale(' + zoom + ')translate(' + -x + ',' + -y + ')')
      .style('stroke-width', 1.5 / zoom + 'px');
}

// event listener to transition back to D3 map.
$reset.on('click', function (e) {
  $mbMap.fadeOut(600);
  $bottom.removeClass('detail');
  $d3Map.fadeIn(1000);
  $reset.hide();

// remove styling from state geojson featureLayer
  for(var i = 0, ii = overlayLayers.length; i < ii; ++i) {
    mbMap.removeLayer(overlayLayers[i]);
  }

  g.transition()
      .duration(750)
      .attr('transform', 'translate(0,0)scale(1)')
      .style('stroke-width', '1.5px');
});

// get bounds of clicked county geography
// create & style state featureLayer
function getBounds(geojson) {

  var style = {
    fillOpacity: 0.4,
    color: '#666',
    weight: 1.8,
    opacity: 1,
  };

  var featureLayer = L.geoJson(geojson, {
    style: style,
    onEachFeature: function(feature, layer) {
      layer.setStyle({
        fillColor: getColor(layer.feature.properties.r),
      });
    }
  }).addTo(mbMap);
  
  return featureLayer;
}

// get all county bounds for a state, using properties.s
function getState(state) {
  var stateBounds = [];
  for(var i = 0, ii = countyBounds.length; i < ii; ++i) {
    if (countyBounds[i].properties.s === state) {
      stateBounds.push(countyBounds[i]);
    }
  }
  return {type: 'FeatureCollection', features: stateBounds};
}

// set color for mapbox quantile scale
function getColor(d) {
    if (d) {
    return d < 2.699 ? 'rgb(219,217,235)':
           d < 4.5 ? 'rgb(203,201,226)' :
           d < 6.3 ? 'rgb(158,154,200)' :
           d < 8.1 ? 'rgb(117,107,177)' :
                     'rgb(84,39,143)';
    } else {
      return 'rgb(198,198,198)';
    }
}

function style(feature) {
      return {
          fillColor: getColor(feature.properties.r),
          weight: 0.7,
          opacity: 0.5,
          color: '#fff',
          fillOpacity: 0.5
      };
}

function highlightFeature(e) {
    var layer = e.target;

    layer.setStyle({
        weight: 4,
        opacity: 1,
        color: '#fff'
    });
}

function resetHighlight(e) {
    usLayer.resetStyle(e.target);
}

function onEachFeature(feature, layer) {
    layer.on({
        mouseover: highlightFeature,
        mouseout: resetHighlight
    });
}

// Debounce function to limit number of function calls
function debounce(func, wait, immediate) {
  var timeout;
  return function() {
    var context = this, args = arguments;
    var later = function() {
      timeout = null;
      if (!immediate) func.apply(context, args);
    };
    var callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) func.apply(context, args);
  };
};
              
            
!
999px

Console