Project Avant Facebook Page Project Avant Twitter Page

tutorial #4: tooltips

Tooltips provide supplemental information from the “title” attribute or the “alt” attribute image, when the user hovers over the aforementioned elements. Although, tooltips are common in web browsers, jQuery allows them to be customized as in the demonstration here that uses a list of smartphones.

In this demonstration, you will learn how to make Tooltips. You will know how to build the jQuery code needed by learning the purpose of each line. Also, you will learn how to create the elements needed to customize a Tooltips in HTML and CSS.

Below is the demonstration of Tooltips. Move the cursor so that it hovers over each smartphone name. You will see the specific mobile operating system that each smartphone is using.

The How-To

HTML

                 
<div id="smartphone-list">								
<ol>

<li>
<a href="#" class="mobile-os" title="Mobile Operating System - iOS">
Apple iPhone 5</a></li> <li> <a href="#" class="mobile-os" title="Mobile Operating System - Blackberry 10">
Blackberry</a></li> <li> <a href="#" class="mobile-os" title="Mobile Operating System - Android">
Samsung Galaxy S5</a></li> <li> <a href="#" class="mobile-os" title="Mobile Operating System - Windows Phone 8">
Nokia Lumia 930</a></li> </ol> </div>

CSS


ol, ul {
list-style: none;
}

#smartphone-list {
	display:block;
}
.tooltip {
  display: none;
  background: #C1CBD1;
  border: #155a7a medium solid;
  position: absolute;
  padding: 5px;
}

jQuery

$(document).ready(function(){//The document is ready.
  $('.mobile-os').hover(function(event){ 
//Selects all elements with a class attribute of "mobile-os" and creates a hover event.
    var titleText = $(this).attr('title');
	//Sets a variable that will grabs the title attribute.
    $(this)
      .data('tipText', titleText)//Creates data for the textText.
      .removeAttr('title');//Removes the title attribute.
      
    $('<p class="tooltip"></p>')//Inserts a 'p' tag
      .text(titleText)//Adds the text in the 'p' tag.
      .appendTo('body')//Adds the p tag to the body.
      .css('top', (event.pageY - 10) + 'px')
	  //Positions the top of the paragraph by 10px.
      .css('left', (event.pageX + 20) + 'px')
	  //Positions the left of the paragraph by 20px.
      .fadeIn('slow');//Fades in the tooltips slowly.
  }, function() {
    $(this).attr('title', $(this).data('tipText'));//Add the 'title' back.
    $('.tooltip').remove();//
  }).mousemove(function(event){//Triggers mousemove event.  
    $('.tooltip')
      .css('top', (event.pageY - 10) + 'px')
	  //Positions the top of the mousemove event by 10px.   
      .css('left', (event.pageX + 20) + 'px');
	  //Positions the left of the mousemove event by 20px.
  });
});//Close.