How to Create an Interactive Graph using CSS3 & jQuery

Interactive Graph

Topic: jQuery (Flot) & CSS3
Difficulty: Advanced
Estimated Completion Time: 1 hour

In this tutorial we will code an Interactive Graph using jQuery and CSS3. We will use the jQuery’s popular plotting plugin “Flot”. Flot is a pure JavaScript plotting library for jQuery. It produces graphical plots of arbitrary datasets on-the-fly client-side. This plugin is simple but powerful enough to create some nice and interactive graphs. For more info take a look at documentation here. You can find the design of the graphs on Impressionist UI made by Vladimir Kudinov.

Step 1 – HTML Markup

To start we will create our html markup for the graph. We will create a <div> with the class “graph-wrapper”. Inside of this <div> we will add two more <div>. The first one will have the “graph-info” class, this div will contain the graph legend and the buttons that will allow us to switch between graphs. The second div will contain the two graphics (lines and bars).

<!-- Graph HTML -->
<div id="graph-wrapper">
	<div class="graph-info">
		<a href="javascript:void(0)" class="visitors">Visitors</a>
		<a href="javascript:void(0)" class="returning">Returning Visitors</a>

		<a href="#" id="bars"><span></span></a>
		<a href="#" id="lines" class="active"><span></span></a>
	</div>

	<div class="graph-container">
		<div id="graph-lines"></div>
		<div id="graph-bars"></div>
	</div>
</div>
<!-- end Graph HTML -->

Step 2 – jQuery and Flot Plugin

Let’s include the JavaScript now. Firs think we need to add is the jQuery Library. I will link to the one hosted by Google. You can link to that one too or download it and host on your server. Then download the “Flot” files and include the “jquery.flot.min.js”. We will also add another script tag and there we will add all the scripts to make our graphs work.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="js/jquery.flot.min.js"></script>
<script>
$(document).ready(function () {
	// Graph scripts here
});
</script>

Step 3 – Graph Data

The data of a graph is an array with data series (ex: [series1, series2, … ]). A series can be either raw data or an object with properties (ex: [ [x1, y1], [x2, y2], … ]). We will also set some custom options for each data.

var graphData = [{
		// Visits
		data: [ [6, 1300], [7, 1600], [8, 1900], [9, 2100], [10, 2500], [11, 2200], [12, 2000], [13, 1950], [14, 1900], [15, 2000] ],
		color: '#71c73e'
	}, {
		// Returning Visits
		data: [ [6, 500], [7, 600], [8, 550], [9, 600], [10, 800], [11, 900], [12, 800], [13, 850], [14, 830], [15, 1000] ],
		color: '#77b7c5',
		points: { radius: 4, fillColor: '#77b7c5' }
	}
];

Step 4 – Load Graphs

Now we will load the two graphs, the one with lines and the one with bars. Both of them have some custom options (colors, shadows, etc.). Also bot of theme use the same data, from the “graphData” variable.

Best Designed WordPress and Bootstrap Themes

Designmodo Shop

// Lines
$.plot($('#graph-lines'), graphData, {
	series: {
		points: {
			show: true,
			radius: 5
		},
		lines: {
			show: true
		},
		shadowSize: 0
	},
	grid: {
		color: '#646464',
		borderColor: 'transparent',
		borderWidth: 20,
		hoverable: true
	},
	xaxis: {
		tickColor: 'transparent',
		tickDecimals: 2
	},
	yaxis: {
		tickSize: 1000
	}
});

// Bars
$.plot($('#graph-bars'), graphData, {
	series: {
		bars: {
			show: true,
			barWidth: .9,
			align: 'center'
		},
		shadowSize: 0
	},
	grid: {
		color: '#646464',
		borderColor: 'transparent',
		borderWidth: 20,
		hoverable: true
	},
	xaxis: {
		tickColor: 'transparent',
		tickDecimals: 2
	},
	yaxis: {
		tickSize: 1000
	}
});

Step 5 – Graph Container Styles

First of all we will add some reset styles to clear the browser defaults.

/* Resets */
.graph-container,
.graph-container div,
.graph-container a,
.graph-container span {
	margin: 0;
	padding: 0;
}

Second of all we’ll add the gradient and the rounded corners. As you can see we are repeating the same properties over again, we need to do this because this CSS3 features are in test in some browsers and the default property will not work, so we need to add vendor prefixes for each browser. This gradient and border-radius will also be used by the tooltips and buttons.

/* Gradinet and Rounded Corners */
.graph-container, #tooltip, .graph-info a {
	background: #ffffff;
	background: -moz-linear-gradient(top, #ffffff 0%, #f9f9f9 100%);
	background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffffff), color-stop(100%,#f9f9f9));
	background: -webkit-linear-gradient(top, #ffffff 0%,#f9f9f9 100%);
	background: -o-linear-gradient(top, #ffffff 0%,#f9f9f9 100%);
	background: -ms-linear-gradient(top, #ffffff 0%,#f9f9f9 100%);
	background: linear-gradient(to bottom, #ffffff 0%,#f9f9f9 100%);

	-webkit-border-radius: 3px;
	-moz-border-radius: 3px;
	border-radius: 3px;
}

To finish this step we will position the graphs container, set the width, height, paddings, etc. Feel free to change these values according to the size you want for the graphs.

/* Graph Container */
.graph-container {
	position: relative;
	width: 550px;
	height: 300px;
	padding: 20px;

	-webkit-box-shadow: 0px 1px 2px rgba(0,0,0,.1);
	-moz-box-shadow: 0px 1px 2px rgba(0,0,0,.1);
	box-shadow: 0px 1px 2px rgba(0,0,0,.1);
}

.graph-container > div {
	position: absolute;
	width: inherit;
	height: inherit;
	top: 10px;
	left: 25px;
}

.graph-info {
	width: 590px;
	margin-bottom: 10px;
}

Step 5

Step 6 – Graph Legend & Buttons

We’ll start to add the basic styles for the links.

.graph-info a {
	position: relative;
	display: inline-block;
	float: left;
	height: 20px;
	padding: 7px 10px 5px 30px;
	margin-right: 10px;
	text-decoration: none;
	cursor: default;
}

For the legends of the graph’s data we will create a small circle with the same color as the lines/bars on the graph. To create this circle we will use the :before pseudo-selector. This selector allows us to add content before the element.

/* Color Circles */
.graph-info a:before {
	position: absolute;
	display: block;
	content: '';
	width: 8px;
	height: 8px;
	top: 13px;
	left: 13px;
	-webkit-border-radius: 5px;
	-moz-border-radius: 5px;
	border-radius: 5px;
}

.graph-info .visitors { border-bottom: 2px solid #71c73e; }
.graph-info .returning { border-bottom: 2px solid #77b7c5; }

.graph-info .visitors:before { background: #71c73e; }
.graph-info .returning:before { background: #77b7c5; }

Then we will style the two buttons that will allow us to toggle between the lines and bars graph. We’ll set a fixed width and height, add the icons images and add a new green gradient for the active state.

/* Lines & Bars Buttons */
#lines, #bars {
	width: 34px;
	height: 32px;
	padding: 0;
	margin-right: 0;
	margin-left: 10px;
	border-bottom: 2px solid #71c73e;
	float: right;
	cursor: pointer;
}

#lines.active, #bars.active {
	background: #82d344;
	background: -moz-linear-gradient(top, #82d344 0%, #71c73e 100%);
	background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#82d344), color-stop(100%,#71c73e));
	background: -webkit-linear-gradient(top, #82d344 0%,#71c73e 100%);
	background: -o-linear-gradient(top, #82d344 0%,#71c73e 100%);
	background: -ms-linear-gradient(top, #82d344 0%,#71c73e 100%);
	background: linear-gradient(to bottom, #82d344 0%,#71c73e 100%);
}

#lines span, #bars span {
	display: block;
	width: 34px;
	height: 32px;
	background: url('../img/lines.png') no-repeat 9px 12px;
}

#bars span { background: url('../img/bars.png') no-repeat center 10px; }

#lines.active span { background-image: url('../img/lines_active.png'); }

#bars.active span { background-image: url('../img/bars_active.png'); }

To finish this step we will clear the floats of the graphs container.

/* Clear Floats */
.graph-info:before, .graph-info:after,
.graph-container:before, .graph-container:after {
	content: '';
	display: block;
	clear: both;
}

Step 6

Step 7 – Graph Toggle

In this step we’ll add the click event for the “bars” and “lines” buttons. On load we’ll hide the “bars” graph, then it will be visible when the users click on the “bars” button. To see the lines graph the user will need to click on the “lines” button.

$('#graph-bars').hide();

$('#lines').on('click', function (e) {
	$('#bars').removeClass('active');
	$('#graph-bars').fadeOut();
	$(this).addClass('active');
	$('#graph-lines').fadeIn();
	e.preventDefault();
});

$('#bars').on('click', function (e) {
	$('#lines').removeClass('active');
	$('#graph-lines').fadeOut();
	$(this).addClass('active');
	$('#graph-bars').fadeIn().removeClass('hidden');
	e.preventDefault();
});

Step 8 – Typography

In this step we will add the typography styles, for links, legends and tooltips.

#tooltip, .graph-info a {
	font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
	font-weight: bold;
	font-size: 12px;
	line-height: 20px;
	color: #646464;
}

.tickLabel {
	font-weight: bold;
	font-size: 12px;
	color: #666;
	font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
}

We will hide the first and last “label” from the y axis, to do that we will use the first and last pseudo-selectors.

.yAxis .tickLabel:first-child,
.yAxis .tickLabel:last-child { display: none; }

Step 8

Step 9 – Tooltip

To add the tooltip we’ll append to the <body> a <div> with the id=”tooltip”. The position of this tooltip will be calculated based on the position of the hovered point of the graph.

function showTooltip(x, y, contents) {
	$('<div id="tooltip">' + contents + '</div>').css({
		top: y - 16,
		left: x + 20
	}).appendTo('body').fadeIn();
}

var previousPoint = null;

$('#graph-lines, #graph-bars').bind('plothover', function (event, pos, item) {
	if (item) {
		if (previousPoint != item.dataIndex) {
			previousPoint = item.dataIndex;
			$('#tooltip').remove();
			var x = item.datapoint[0],
				y = item.datapoint[1];
				showTooltip(item.pageX, item.pageY, y + ' visitors at ' + x + '.00h');
		}
	} else {
		$('#tooltip').remove();
		previousPoint = null;
	}
});

Then we will add a position absolute, hide it using the display property and add some padding and a nice border.

#tooltip {
	position: absolute;
	display: none;
	padding: 5px 10px;
	border: 1px solid #e1e1e1;
}

Step 9

Conclusion

That is it. We have finished this tutorial, fell free to customize this graph with CSS and all the possibilities that Flot plugin offers. Don’t forget to subscribe us for more articles, tutorials and freebies.

Preview

Subscribe to Unlock

Subscribe to our newsletter to get access to this content. Your email will not be sold/rented. Unsubscribe at any time.
- required fields

Enter the e-mail, which was subscribed

After that, the content becomes available again!
- fields are mandatory

On your email was sent a letter

Simply click on the link in the email and you will get access to the hidden content!

There is no information about this email in our database. Please subscribe by clicking on button below.

Your e-mail is not in our database. Subscribe by clicking the button below
I'm already a subscriber

Impressionist UI - User Interface Pack

Valeriu is a Web Designer & Front-End Developer currently living in Lisbon, Portugal. He creates some cool stuff using CSS3 and HTML5. You can follow him on @vtimbuc, Google+ or visit his web site at vtimbuc.net.

Newsletter

32 Comments
  1. codee47 Aug 22, 2:27 pm

    Fantastic, thanks for sharing.

    Reply
    +2
  2. Mrinal Aug 22, 7:42 pm

    Love to know it, thanks for sharing. Good one.

    Reply
    0
  3. pr Aug 22, 8:59 pm

    Nice flot customization. Thanks for sharing!

    Reply
    0
  4. Jerry Aug 22, 9:35 pm

    Great tutorial, thanks.

    Reply
    +1
  5. Steve Aug 22, 10:27 pm

    Doesn’t work at all in IE8

    Reply
    0
    • Adrian Aug 22, 10:45 pm

      Maybe, thank you for testing. Will be good do not pay attention for old browsers, because very small people use these type of browsers. Anyway, good remark.

      Reply
      +1
    • Valeriu Aug 22, 11:14 pm

      IE8 is a old browser, is time to move on ;)

      Reply
      +2
    • Steve Aug 23, 4:15 am

      IE7 is old, IE8 isn’t very old. Telling your customers to “move on” doesn’t fly.

      Reply
      -4
      • Adrian Aug 23, 9:50 am

        DesignModo example: IE 8 used by 1.5% and IE 7 by 0.1 of visitors and i think these visitors access site occasionally. Very poor results to pay attention and refuse the new technologies…

        Reply
        0
      • Steve Garvey Aug 23, 8:20 pm

        Our portal stats are more like IE7: 20% (corporate users who are not allowed to upgrade their machines or install other browsers). The users visiting a web design focused site are hardly representative. These stats are probably more accurate: IE7+IE8 ~15%

        http://www.w3counter.com/globalstats.php

        You’re gonna tell a client to toss 15% of sales because CSS3 is just so damn cool?

        Reply
        +2
        • Adrian Aug 23, 8:30 pm

          “You’re gonna tell a client to toss 15% of sales because CSS3 is just so damn cool?”

          sure not! in this case you can try other possibilities, but we don’t leave to write about new technologies, we need to make progress.

          Reply
          0
          • Mark Feb 20, 5:38 am

            You can still use flot with IE7+. You need to include the excanvas.js file from Google and use an if comment to include the excanvas.js file. Google excanvas.js for the correct syntax.

            +2
        • Krasimir Sep 2, 5:48 pm

          “(corporate users who are not allowed to upgrade their machines or install other browsers).”
          This is Your corporation problem and not anyone else – the world and technologies are going forward so Your corporation should do it as well?

          Reply
          -2
          • obcali Sep 4, 8:28 pm

            @Krasmir, etc: We always try to push technology and better the experience of all users. However, it is a reality that large corporations have to move slower due to their size. Trying to turn a cruise ship around takes more space and time than a small speedboat. Accordingly, it is not so much a “corporation problem”, rather the fact that big firms need time to integrate technologies and new software, and usually take time to make sure that they are doing what’s stable, proven, and not what’s “hot” when it affects tens of thousands of their own employees (most of which are not involved in web as their own professions like us). We need both innovation and also patience in this field.

            +3
          • Valeriu Sep 6, 3:30 am

            You are right that usually to upgrade the software of all the machines of a corporation is a pain in the ***. So if I was asked to do it for a corporation I would off course support older browser like IE8. But when we do a tutorial we always have to look forward and use the latest technologies available.

            -1
    • Aske Oct 24, 11:41 am

      You can try using Excanvas polyfill for drawing canvas elements in IE8 – https://code.google.com/p/explorercanvas/

      Reply
      0
  6. Cristi Oct 11, 11:59 pm

    Very, very cool. Was wondering if you could display multiple Google Analytics profiles like that. You certainly can and I did it. Not a tutorial by any means, but the code (and a screenshot) is here: http://squaresquirrel.ro/web/monitoring-multiple-google-analytics-profiles-2012/
    Thank you for this, it was a fun project ;)

    Reply
    +1
  7. Aditya Oct 17, 12:53 pm

    Thanks a lot for sharing this. I am a novice when it comes to all this coding but I could understand the basic crux of the code. I have one concern though, if you could clear that I would be grateful.

    Instead of hovering over the data points and then getting the information in the box, I wanted the user to click on the points, I tried changing the same in the JS but am doing something wrong. Can you please guide me?

    Reply
    -1
  8. Agus Darmaputra Nov 13, 3:11 am

    Hi, is there a way to grab the data we wanna show from database (MySQL)?
    Sorry for the newbie question..

    Reply
    +1
    • Adrian Nov 13, 12:07 pm

      Nope, it is only css3+jquery.

      Reply
      0
      • Mark Feb 20, 5:35 am

        Sure you can hook up flot to mysql. You just need to know how to do it. I would use JQuery .ajax to perform a get to a php, jsp, asp page and return a JSON string. Then json encode the string and use it as data for Flot. Just go through it step by step and you can make it work.

        Reply
        +1
  9. Error while running this Nov 27, 10:25 pm

    hi,
    i exactly copied and paste the code but when I run this , i get an exception on ln – 11754 in flot.min.js
    “throw”Invalid dimensions for plot, width…..”

    I couldnt get what is wrong. please help

    Reply
    +2
    • Philippe Jan 5, 4:13 pm

      Hi,

      I just had the same problem. After some research I’ve found that my css ID in the HTML was in lower case letters, whereas the float script was looking for the ID in capital letters. That triggered the “invalid dimension” error.

      Reply
      +2
  10. Alexandre Catalán Mar 14, 9:05 pm

    Hi,

    Good tutorial, it is possible to apply a ‘fill’ white, a red border, and a white border?

    ex:
    http://dribbble.s3.amazonaws.com/users/2965/screenshots/943079/attachments/106141/dbreal.jpg

    Reply
    -1
  11. Guntar Mar 21, 7:12 am

    This tutorial is marvelous. Thank you verymuch for writing this :-)

    Reply
    0
  12. Sreejesh May 26, 9:14 am

    Thank you for sharing such a great tutorial. Can I use it show month names in x-axis? How it can be passed to data.

    Reply
    +3
  13. Gaspar Laprida Sep 20, 6:02 am

    Hi, great tutorial!

    I was wandering if you could please help me to make it ‘responsive’.

    I guess you know what I mean, but I’ll explain it anyway.
    What I want is a chart (only Line Chart in my case) that resizes along with the browser window.

    Thanks in advance!

    Reply
    -1
  14. Etron Jan 11, 6:45 pm

    How do I put text: // Visits
            data: [ [‘January’, 1300], etc..

    Reply
    +3
  15. Sašo Jan 12, 10:23 pm

    Hei..very useful! I like it…

    I have one question about it…

    if I add new value into visits (lthird value), how can I display it into tooltip? Now I can display first and second value into tooltip, but if I add third value I cannot display it :/

    // Visits
    data: [ [6, 1300, 1], [7, 1600,2], [8, 1900,3], [9, 2100,3], [10, 2500,1], [11, 2200,44], [12, 2000,55], [13, 1950,4], [14, 1900,7], [15, 2000,9] ],

    Reply
    +4
  16. Cassy Jan 21, 12:15 pm

    I have data coming back to me in JSON format.
    Please, can someone help me make the graph use JSON data?

    Thanks.
    Cassy.

    Reply
    -2

Leave a Reply

*
* Minimum length: 20 characters