How to Create a Basic jQuery Tool Tip Plugin

If you have had anything to do with web development of late, you hardly need an introduction to either jQuery or jQuery plugins. In fact, jQuery plugins have become so popular that nearly 70% of the internet makes use of them in some way or the other. Novice or Pro, whatever your level of web development expertise might be, jQuery should definitely be on your list of things to learn and master. With this in mind, in this tutorial, we will teach you how to create a basic jQuery Tool Tip Plugin.

So, this is what we will be creating:

jQuery Tooltip preview screenshot

Without wasting anymore time, let’s get our hands dirty with some awesome coding and master the creation of a jQuery plugin.

The File Structure

  1. jqueryToolTip.css – Stylesheet of the tooltip.
  2. jqueryToolTip.js – The actual jQuery plugin file.

We need to ensure that our plugin is flexible enough so that it can serve a variety of users and device configurations without any hassles. Before going any further, we will take a look at some rules or concepts that will help us accomplish this.

Rules For Creating A jQuery Plugin

  1. Keep Identities Unique – It is very important to have unique id and class names so that at the time of styling your plugin elements, you are not overriding the current page styles.
  2. Leave line comments – Leaving line comments is always good practice. This is essential when dealing with jQuery plugins, because users and programmers may find it difficult to figure out what each line of code written by someone else means, amd trying to decipher the code without comments can be time-consuming.
  3. Minify Source Code – As your plugin is not the only thing required to create a website, its important to use as little space and bandwidth as possible for the end user.

While there is no rigid rule for it, while coding, I personally take care of the designing part before making my code functional. We will follow the same model in this tutorial: we will write the required HTML and CSS first before we get to writing the code for the actual jQuery Tool Tip Plugin.

Create a sample .html file and add the following code to it.

<div id="jqueryToolTip_wrapper">
    <span class="jqueryToolTip_text">Tooltip Text Goes Here </span>
    <span class="jqueryToolTip_arrow"></span>
</div><!-- end jqueryToolTip -->
1

<p>Now open the <code>jqueryToolTip.css</code> file and paste the below CSS inside it.</p>

1

<p>Make sure you include the <code>.css</code> file inside your sample <code>.html</code> file and then open the <code>.html</code> file using a browser. If everything goes fine, you will be able to see a nice looking tooltip with an up arrow quite similar to the image given below.</p>

<p><img src="http://speckyboy.com/wp-content/uploads/2012/10/jquerytooltip2.jpg" alt="jQuery Tooltip preview screenshot" /></p>


<h2>ToolTip With Down Arrow</h2>

<p>In order to add a down arrow to the same tooltip, all you need to do is add class <code>.arrow_down</code> to the span with existing class <code>.jqueryToolTip_arrow</code></p>

<p>Before:</p>
1<span class="jqueryToolTip_arrow"></span>

After:

<span class="jqueryToolTip_arrow arrow_down"></span>

Requirements

Now that we are done with the HTML and CSS part, we can take some time to understand the requirements before we actually plunge into writing the code for the plugin.

  1. We need to find out which element to target (because we cannot show the tooltip on every single anchor link).
  2. We need to grab the X and Y axis on the current anchor link in hover state.
  3. Finally, we need to re-position our tooltip div to the current anchor link in hover state.

This might seem complicated but jQuery filters and CSS targeting elements will make our job a lot easier.

Basics of jQuery Plugins

WrapUp Code:

		(function($  ){
			$  .fn.jqueryToolTip = function(toolTipOptions){
			}
			}
		})(jQuery);

The code given above is what you need to use everytime you start creating a plugin from scratch. Here jqueryToolTip is the plugin name and can be replaced by anything you want. Try to keep it unique as two plugins with the same name can create a huge mess.

Default Settings:

		var toolTipDefaults = {
			position:"bottom"
		},

Depending upon your plugin, you may need to have some default settings. For example, in our tutorial, position is something we need to take care of (that is, whether we want to show the tooltip on top of the element or below it).

Overriding Defaults:

		toolTipSettings = $  .extend({}, toolTipDefaults, toolTipOptions);

It is always a good practice to let the end users override the default settings if they so desire. In our case, we have set the tooltip to be on the bottom by default. Now, if the end user wants it to be on top, the above code will override the default settings with the options specified by the end user.

Apart from what we have discussed above, everything else is plain jQuery code. So, we can now get started! Simply open jqueryToolTip.js file and place the following code inside it.

		(function($  ){
			$  .fn.jqueryToolTip = function(toolTipOptions){
				var toolTipDefaults = {
					position:"bottom"
				},
				toolTipSettings = $  .extend({}, toolTipDefaults, toolTipOptions);
				var toolTipTemplate = '<div id="jqueryToolTip_wrapper"><span class="jqueryToolTip_text"></span><span class="jqueryToolTip_arrow"></span></div><!-- end jqueryToolTip -->';
				$  ('body').append(toolTipTemplate);
			}
		})(jQuery);

We have created a variable called toolTipTemplate which is going to contain the HTML markup for our jQuery ToolTip Plugin. Thereafter, we will append the HTML markup to the body of a webpage.

		$  (this).each(function(){
			$  (this).hover(function(){
				// here goes the code for actions that occur after hovering over the link
			});
		});

$ (this) is the reference to the element that will initiate our plugin. Everytime the end user’s cursor hovers over the required element, we will show the tooltip and change the text inside it to the title attr of the link.

		$  (this).each(function(){
			// on hover function
			$  (this).hover(function(){
				var toolTipTitle = $  (this).attr("title"); // getting current link title
				var toTop = $  (this).offset().top; // getting current link Y axis
				var toLeft = $  (this).offset().left; // getting current link X axis
				var toolTipHeight = $  ('#jqueryToolTip_wrapper').css("height"); // getting toolTip Height
				var itemHeight = $  (this).css("height"); // getting link Height

				if(toolTipSettings.position == 'top')
				{
					$  ('#jqueryToolTip_wrapper').find('.jqueryToolTip_arrow').addClass('arrow_down');
					var topFinal = parseInt(toTop) - parseInt(toolTipHeight) - 10;
				}
				else
				{
					var topFinal = parseInt(toTop) + parseInt(itemHeight) + 10;
				}

				$  ('.jqueryToolTip_text').html(toolTipTitle); // changing tooltip text to current link title
				$  ('#jqueryToolTip_wrapper').css("display","block"); // setting tooltip display to block
				$  ('#jqueryToolTip_wrapper').css({   // setting tooltip left and top position to the current link position
					top: topFinal,
					left: toLeft
				});
			},function(){
				$  ('#jqueryToolTip_wrapper').css("display","none");  // hiding tooltip after hover is done
			});
		});

In the above code, I have commented on each and every line in order to give you a better understanding of what the given code is trying to do.

Putting It All Together

		(function($  ){
			$  .fn.jqueryToolTip = function(toolTipOptions){

				// default settings for the plugin
				var toolTipDefaults = {
					position:"bottom"
				},

				// extending default settings
				toolTipSettings = $  .extend({}, toolTipDefaults, toolTipOptions);

				// HTML markup for tooltip plugin
				var toolTipTemplate = '<div id="jqueryToolTip_wrapper"><span class="jqueryToolTip_text"></span><span class="jqueryToolTip_arrow"></span></div><!-- end jqueryToolTip -->';

				// appending the markup
				$  ('body').append(toolTipTemplate);

				$  (this).each(function(){
					// on hover function
					$  (this).hover(function(){
						var toolTipTitle = $  (this).attr("title"); // getting current link title
						var toTop = $  (this).offset().top; // getting current link Y axis
						var toLeft = $  (this).offset().left; // getting current link X axis
						var toolTipHeight = $  ('#jqueryToolTip_wrapper').css("height"); // getting toolTip Height
						var itemHeight = $  (this).css("height"); // getting link Height

						if(toolTipSettings.position == 'top')
						{
							$  ('#jqueryToolTip_wrapper').find('.jqueryToolTip_arrow').addClass('arrow_down');
							var topFinal = parseInt(toTop) - parseInt(toolTipHeight) - 10;
						}
						else
						{
							var topFinal = parseInt(toTop) + parseInt(itemHeight) + 10;
							$  ('#jqueryToolTip_wrapper').find('.jqueryToolTip_arrow').removeClass('arrow_down');
						}

						$  ('.jqueryToolTip_text').html(toolTipTitle); // changing tooltip text to current link title
						$  ('#jqueryToolTip_wrapper').css("display","block"); // setting tooltip display to block
						$  ('#jqueryToolTip_wrapper').css({   // setting tooltip left and top position to the current link position
							top: topFinal,
							left: toLeft
						});
					},function(){
						$  ('#jqueryToolTip_wrapper').css("display","none");  // hiding tooltip after hover is done
					});
				});
		}
		})(jQuery);

How to Call the Plugin

Calling our jqueryToolTip plugin is as simple as any other jQuery plugin.

Include JS File:


<p>Include Style Sheet:</p>
1<link rel="stylesheet" href="../Documents/Unzipped/jqueryToolTipPluginTutorial/jqueryToolTipPluginTutorial/jqueryToolTip.css" />

Create an anchor link with title attribute:

<a href="#" title="ToolTip Demo">ToolTip Demo</a>

Calling the Plugin (Basic):

<script type="text/javascript">
    $  (function(){
        $  ('a').jqueryToolTip();
    })
</script>

Calling the Plugin (Passing Options):

<script type="text/javascript">
    $  (function(){
        $  ('a').jqueryToolTip({
            position:"top"
        });
    })
</script>

Finished!

jQuery Tooltip preview screenshot

You might also like…

Rearrange content when it’s too wide with jQuery →
Coding the Digg v4 Layout with HTML5 and CSS3 →
How to Build an Accordion Image Gallery with only CSS →
Scroll to Internal Link with jQuery →
How to Build a Sliding One Page Portfolio with jQuery →
Hoverizr – An in depth view of the jQuery plugin →
Rubber Layouts – Combining Static and Fluid Layouts →
How to Build a Fully Functional CSS3-Only Content Slider →
Resize Images in a Post with jQuery, and turn it into a plugin →
Getting Started with WordPress Shortcodes (+Examples) →



Speckyboy Design Magazine

Leave a Comment