D3.js alternating background plotbands

In this example below you will see how to do a D3.js alternating background plotbands with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by siriusastrebe, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright siriusastrebe ©

Technologies

  • HTML
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>D3.js alternating background plotbands</title>
  
  
  
  
  
</head>

<body>

  <button onclick="pause()">Pause</button>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js'></script>

  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/siriusastrebe/d3js-alternating-background-plotbands-GrqBQb */
var width = 800
var height = 300
var chart = d3.select('body').append('svg')
   .attr('width', width + 30)
   .attr('height', height + 30)
   .style('background-color', '#F0F0F0')

function randomDates() {
   var today = new Date()
   var max = new Date(new Date().setFullYear(today.getFullYear() + 3))
   var random = new Date(today.getTime() + Math.random() * (max.getTime() - today.getTime()))

   return [today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate(), random.getFullYear() + '-' + (random.getMonth() + 1) + '-' + random.getDate()]
}

var interval = setInterval(function () {
   var dates = randomDates()
   render(dates)
}, 5000)

function pause () {
  clearInterval(interval)
}

var xScale = d3.scaleTime()
var xAxis = chart.append('g').attr('class', 'xAxis')
   .attr('transform', 'translate(0, ' + (height) + ')')

function render(data) {
   xScale
      .domain(d3.extent(data, function (d) { return new Date(d) }))
      .range([15, width])

   var xLabel = d3.axisBottom()
     .tickSizeInner(-height)
     .tickPadding(8)
     .scale(xScale)

  xAxis
      .transition()
      .duration(2500)
      .call(xLabel)
  
   var xAxisLines = chart.selectAll('.xAxis line')
   var xAxisNodes = xAxisLines.nodes()

   // This creates the alternating dark gray background that snaps to each month
   xAxisLines
      .transition()
      .duration(2500)
      .attr('stroke', function (d, i) { return i % 2 ? '#DDD' : 'transparent'})
      .attr('transform', function (d, i) {
         if (i % 2) { return 'translate(' + - getPaneLength(d, i) / 2 + ', 0)' }
         else return ''
      })
      .attr('stroke-width', function (d, i) {
         if (i % 2) { return getPaneLength(d, i) }
         else return 0
      })
  
   function getPaneLength (d, i) {
     var prevDate = xAxisNodes[i - 1].__data__
     var length = xScale(d.getTime()) - xScale(prevDate)

     return length
   }
}

Comments