WebAppers

/ best free open source web resources /

Shopify

Create a Content Rich Tooltip with JSON and jQuery

Posted · Category: License Free, Tooltips

Today we’re going to break the mold of the traditional tooltip. This tutorial will demonstrate how to build tooltips that are powered by jQuery, with information pulled from a JSON array. Here’s a look at the final result that we’ll be looking to make:

The end result

Our page will have two links. When a user hovers over a link, it will trigger the top banner to change its background image and text based on the entry in a JSON array. See the Demo

We’ll be using a pack of background images in later steps. You can grab those here.

Build the Page Structure

New File: I have called my HTML file ‘json-tooltip.htm” for this tutorial

Our example’s HTML is pretty self explanatory. We’re just blocking out a banner to contain the tooltip information, and then placing all of the normal content below.

Pay special attention to what’s going on with link anchors with a class of “tooltip” though. This is the class that will designate which links are tooltips. Also, you’ll notice that the “rel” attribute contains a number. This is the number we’ll use to associate a specific tooltip to an anchor link. This will become clear in a few steps.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
		"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

	<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

		<title>jQuery/JSON Tooltip Demo</title>

		<link rel="stylesheet" href="json-tooltip.css"/>

		<!--Load up jQuery Library-->
		<script src="http://code.jquery.com/jquery-latest.js"></script>
		<script type="text/javascript" src="json-tooltip.js"></script>

	</head>

	<body>
		<div id="wrapper">

			<div id="banner">
					<h1>Go On</h1>
					<p>Hover over a link below</p>
			</div>

			<p>The link in this sentence will <a href="#" class="tooltip" rel="0">display a tooltip</a> on hover.</p>

			<p>If you're feeling adventurous, you could always give<a href="#" class="tooltip" rel="1">this link a try</a> too!</p>

		</div>

	</body>
	</html>

Size and Style with CSS

New File: I have called my CSS file ‘json-tooltip.css” for this tutorial

Since the bulk of this layout will be done in jQuery, the CSS is only responsible for sizing the banner div to proper size. I’ve also included optional font styles for presentation sake.

*{margin:0; padding:0;}

	body{font-family:georgia; background:#191919;}

		p{padding:0px 30px; font-size:13px; margin-bottom:15px; line-height:1.6em;}

		a{padding:3px 6px; background:#333; color:#FFF; margin:0px 3px; text-decoration:none;}
			a:hover{color:#FFC125;}

	#wrapper{margin:10px auto; width:960px; padding-bottom:30px; background:#FFF; border:1px solid ##F7F7F7;}
		#banner{background:#DDD url('purple-bg.jpg') no-repeat top left; height:300px; text-align:center; margin-bottom:30px; border-bottom:1px solid #CCC;}
			#banner h1{padding:55px 0px 15px 0px; font-size:60px; font-family:Arial, sans-serif; letter-spacing:-3px}
			#banner p{color:#333; font-size:16px;}

The Logic Behind JSON

Some of you may ask “Why use JSON to populate the ‘tooltip’?” The average Javascript tooltip is populated by the contents of the “title” attribute of the anchor link. This is a great approach for text only tooltips, but if you’re looking to add more information it can get a little messy.

This tutorial demonstrates one way that your tooltips can activate full body content changes using arrays, rather than pulling from various hidden elements on the page. This way we can include any number of elements to the layout besides text.

If you’re new to JSON, don’t panic. It is essentially a very simple way to build and access arrays in Javascript, much in the style of its PHP counterparts. You can also read a more comprehensive primer here for more.

Create Array with JSON

New File: I have called my Javascript file ‘json-tooltip.js” for this tutorial

For the sake of simplicity, there are only two entries in the tooltips array for this tutorial. As you can see below, each contains three fields:

1. A title (“Title”) to be loaded into the banner’s h1 tag.
2. The content (“Content”) to be loaded in the banner’s p tag.
3. An image url (“ImageURL”) to be loaded as the banner’s background.

Paste the code below into the top of your JS file to establish the tooltip array

//JSON banner content array
	var banner_data = {
		//Tooltips
		"tooltips" : [

			//Remember that the count starts at zero

			{
				//Array ID -> 0
				"Title"   : "Oh Yes", 
				"Content" : "That's some good hovering.",
				"ImageURL"   : "yellow-bg.jpg"
			},

			{
				//Array ID -> 1
				"Title"   : "Nice", 
				"Content" : "You found link number 2",
				"ImageURL"   : "orange-bg.jpg"
			}

		] 
	}

Preload Images with jQuery

This is a quick fix to help keep things smooth. Because the jQuery will be referencing background images that are not loaded by default, it would be nice to have them preloaded to prevent further hiccups. For this we’re turning to a handle plugin that automatically preloads images once the document is ready.

To implement the preloader, we’ll first need to paste in the following immediately below the JSON array code from the previous step. This code declares a new jQuery preloader method.

// Image Preloader via http://www.innovatingtomorrow.net/2008/04/30/preloading-content-jquery
	jQuery.preloadImages = function()
	{
	  for(var i = 0; i").attr("src", arguments[i]);
	  }
	}
	

Next we’ll need to go through the entire JSON array on document ready and load the images in each entry. The loop I’ve written below will go through each and load the corresponding image, providing it is not empty.

Note: Remember that since this is where the jQuery starts, it goes within the document ready function along with the code from the next step.

//Actual jQuery starts here on document ready
	$(document).ready(function() {


		//Goes through each tooltip's image URL
		for(var i = 0; i < banner_data.tooltips.length; i++){

			image_location = banner_data.tooltips[i].ImageURL;

			//Preload if location exists
			if (image_location != ''){
				$.preloadImages(image_location);
			};

		};


	});

Show Tooltip Contents with jQuery

Here's where we get to the bulk of the jQuery for the page. Tooltips will be activated via hover, and then deactivated when the hover state is removed.

When a tooltip is activated, jQuery will populate the banner with the information from the corresponding JSON entry. This active tooltip is determined by getting the value of the tooltip's rel attribute.

Copy in the code below within the already active document ready function created in the last step.

$('a.tooltip').hover(function(){ //when hover starts

		//Get the ID of the current tooltip
		active_tooltip = $(this).attr('rel');

		//Replace the HTML in the header with data from JSON array
		$('#banner h1').html(banner_data.tooltips[active_tooltip].Title);
		$('#banner p').html(banner_data.tooltips[active_tooltip].Content);
		$('#banner').css("background-image", "url("+ banner_data.tooltips[active_tooltip].ImageURL + ")");

	},
	function(){ //When hover ends

		//Reset banner to defaults
		$('#banner h1').html("Go On");
		$('#banner p').html("Hover over a link below");
		$('#banner').css("background-image", '');

	});

Go ahead and give it a run! If you experience any errors, I recommend checking your results against the demo files available for download.

About the Author

Zach is a co-founder of One Mighty Roar, a web design company that runs a network of blogs centered on creativity. He and his twin brother are behind Build Internet, where he blogs on web design, development and business. Connect with him on Twitter for more.

Requirements: jQuery Framework, JSON
Demo: http://www.webappers.com/demo/json-tooltip/
Download: http://www.webappers.com/download/json-tooltip-final.zip
License: License Free

21 Comments
  • http://www.gigglecomputer.com Phaoloo

    Awesome tip! I knew JSON and jQuery before but never thought about combine them together.

  • Paratron

    I don’t get it… WHERE exactly is now the Tooltip?! I just see the Header-Image switching…

  • http://www.jalokimgraphics.com Jalokim

    Well done this is an awesome tool.
    But I am wondering if we can’t boost this up a bit.

    I was thinking of a fade in as you hover addon to this.
    The hover and image change is pretty awesome, but it flashes quite quickly… I think slowing it down with a fade in and out would make the effect 100 times better?

    thoughts?

  • http://rafyta.com Rafyta

    Pretty cool, I already like you better than net tuts!

  • http://www.creare.co.uk Mandy

    Thank you for sharing this – I think adding a fade would also give it a softer more subtle effect. Is this possible?

  • http://www.jalokimgraphics.com Jalokim

    I have modified the code a bit …
    I think the effect I got is pretty cool…

    now I just need that fade…
    http://testjalcss.7forum.net/forum.htm

  • http://www.buildinternet.com Zach Dunn

    Hey guys,

    Seems like there has been an interest in how this method would work with a fade animation included.

    Making the image fade in this particular case would be a little more difficult, because it is a CSS background instead of image element. I did a little bit of research, but I didn’t manage to come up with anything that allows jQuery to do such an animation naturally. If I’ve overlooked something, please share — I’m as interested as the rest of you.

    The other discussion seems to be about this actually being a “tooltip” or not. The goal of this was to mimic the actions of a tooltip, only using more content as options. I would define a tooltip as information that displays when a user hovers over a predetermined area. If this conflicts with anyone else’s notions of what a tooltip should be, I’m sorry if you felt mislead.

    I just wanted to clear up Paratron’s comment especially, because on first glance this certainly does look like simply an image switching header. If you take a moment to review the code, you’ll hopefully see that it has a bit more to it — most notably the multiple elements in the header switching around.

    Glad to see the responses so far though! Thanks for all the feedback. You guys are wonderful.

  • tzDaFoo

    Man that is one sexy header, somebody’s liable to get knocked out by that one.
    And to think I was just thinking I need to still use my old copy of image ready to do this sort of stuff.
    Sliding doors CSS is sometimes tedious, option #2 or #1 even…
    jQuery Hovers to the rescue!!!

  • Pingback: 25 New jQuery Plugins and Tutorials | oOrch Blog

  • nicke

    hmm, where to use this one?
    tooltips are not normally done like this. me no like

  • Pingback: 10 Kullanışlı jQuery Eklentisi | Ahmet ERTEM

  • Pingback: VECTOR Tutorial

  • Pingback: 40 Free Amazing jQuery Plugins and Tutorials With Demos | DesignBeep

  • Pingback: jQuery slick wrap | WebDesignExpert.Me

  • Pingback: 8º Post: Programación – Francisco Cabezas (@fcocabezas) | MKT Blog

  • Ian

    Sweet mercy where is the demo?

  • Pingback: 30+ Free Amazing jQuery Plugins and Tutorials | WEBAXES.COM

  • chenhuan

    that’s really nice.

  • Hook4free

    Yeah that is good stuff combining JSON and jQuery. Now I’m working with jQuery and PHP and making cool stuff.

  • Pingback: Quick Tip – Reading & Editing HTML Attributes in jQuery | Build Internet

  • http://www.technostall.com/ Chankey Pathak
Supported By

Deals

Web Browsers Icon Set
Food Icon Set
Flat Icon Set

Flat Icon Set

100 icons