css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

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

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

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.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <!DOCTYPE html>
<html>
	<body>
		<script src="https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js"></script>
	</body>
</html>
            
          
!
            
              * {
	box-sizing: border-box;
	font-family: helvetica;
}

html, body {
	margin: 0;
	width: 100vw;
	height: 100vh;
	display: grid;
	place-items: center;	
	background-color: hsl(0, 0%, 30%);
	color: hsl(0, 0%, 10%);
}

#svg-container {
	background-color: hsl(0, 0%, 100%);
	margin: 1rem;
	border-radius: .1rem;
}

.tooltips  {		
    font-size: 20px;		
}
            
          
!
            
              //This is the main ajax call to start the app
//takes a url and mehtodtype and returns a promise
window.onload = () => {
	function ajaxCall(url, methodType) {
		let promObj = new Promise((res, rej) => {
			const xhr = new XMLHttpRequest();
			xhr.open(methodType, url, true);
			xhr.send();
			xhr.onload = () => {
				if(xhr.readyState === 4) {
					if(xhr.status === 200) {
						let resp = xhr.responseText;
						let respJson = JSON.parse(resp);
						res(respJson);
					} else {
						rej(xhr.status);
					}
				}
			}
		});
			return promObj;
	}

	let URL = 'https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json';


	//calls the makeSVG function after it get the data from the url
	ajaxCall(URL, 'GET').then(makeSVG);

	function makeSVG(dataset) {
		//map over gdp numbers 
		const gdps = dataset.data.map((arr) => {
						return arr[1];
					});

		//vars for the SVG elements
		const svgWidth = 900,
					svgHeight = 500,
					padding = 20,
					dataMin = d3.min(gdps),
					dataMax = d3.max(gdps),
					dataLength = dataset.data.length,
					dates = dataset.data.map((x) => {
						return new Date(x[0] + 'T00:00:00');
					}),
					minDate = d3.min(dates),
					maxDate = d3.max(dates);
		//yScale for the GDP
		const yScale = d3.scaleLinear()
											.domain([0, dataMax])
											.range([svgHeight, 50]);
		const yAxis = d3.axisLeft(yScale).tickSizeOuter(0);
		

		//xScale for the year timeScale
		const xScale = d3.scaleTime()
											// input data
											.domain([minDate, maxDate])
											// output data
											.range([50, svgWidth - 50]);
		
		const xAxis = d3.axisBottom(xScale).tickSizeOuter(0);
		
		//This is the main SVG container stored in an const named svg on the 'body' element
		const svg = d3.select('body')
		.append('svg')
		.attr('id', 'svg-container')
		.attr('width', svgWidth)
		.attr('height', svgHeight)
		.style('filter', 'drop-shadow( 0 5px 5px black)');

		//This is the text at the top of the svg to show what the data is for
		//A text element is appended to the SVG element
		svg.append('text')
			.attr('x', 250)
			.attr('y', 50)
			.attr('id', 'title')
			.style('font-size', "40px")
			.style("text-decoration", "underline") 
			.text('United States - GDP');
		
			//Create the toolTip
		let toolTipDate = svg.append('text')
				.attr('class', 'tooltips')
				.attr('id', 'tooltip')
				.attr('x', 250)
				.attr('y', 300)
				.style('opacity', 0);
		
		let toolTipGDP = svg.append('text')
				.attr('class', 'tooltips')
				.attr('x', 250)
				.attr('y', 320)
				.style('opacity', 0);

		//all rect elements
		svg.selectAll('rect')
			.data(dataset.data)
			.enter()
			.append('rect')
			.attr('data-date', (d, i) => {
			return d[0];
		})
			.attr('data-gdp', (d, i) => {
			return d[1];
		})
			.attr('x', (d, i) => {
			return xScale(new Date(d[0] + 'T00:00:00'));
		})
			.attr('y', (d, i) => {
			return yScale(d[1]) - 35;
		})
			.attr('width', (svgWidth - 100) / dataLength)
			.attr('height', (d, i) => {
			return (svgHeight) - yScale(d[1]);
		})
			.attr('fill', '#333333')
			.attr('class', 'bar')
			.on('mouseover', handleMouseOver)
			.on('mouseout', handleMouseOut);
	
	// Format date yyyy-mm-dd -> dd/mm/yyyy
		function formatDate(date) {
				let d = new Date(date),
						day = d.getUTCDate(),
						month = d.getUTCMonth() + 1,
						year = d.getUTCFullYear();
				return `Date: ${day}-${month}-${year}`;
				
			}

		//Make rect color white when mouse hovers
		function handleMouseOver(d, i) {
			d3.select(this).style('fill', '#ffce21');


			toolTipDate.attr('data-date', d[0])
			.text(formatDate(d[0]))
			.style('opacity', 1);;
						 		// .text(formatDate(d[0]));
			toolTipGDP.text(`$${d[1]} Billion`)
			.style('opacity', 1);;
			
		}

		//change rect back to blue color when mouse leaves
		//and remove #tooltip 
		function handleMouseOut(d, i) {
			d3.select(this).style('fill', '#333333');
			toolTipDate.style('opacity', 0);
			toolTipGDP.style('opacity', 0);
		}
		//add the yAxis to a 'g' element
		svg.append('g')
			.attr('id', 'y-axis')
			.attr('transform', 'translate(' +
						50 + ',' + -35 +')')
			.call(yAxis);

		//add the xAxis to a 'g' element
		svg.append('g')
			.attr('id', 'x-axis')
			.attr('transform', 'translate(' +
						0 + ',' + 465 +')')
			.call(xAxis);

	}
}







            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console