tooltip snippets

Positioning an element over another element with jQuery

Tagged jquery, position, absolute, tooltip, dialog  Languages javascript

Positioning an element over another element is a common problem and can be used for creating simple tooltips, inline dialogs, informational messages and so on.

The code is simple:

$.fn.positionOn = function(element, align) {
  return this.each(function() {
    var target   = $(this);
    var position = element.position();

    var x      = position.left; 
    var y      =;

    if(align == 'right') {
      x -= (target.outerWidth() - element.outerWidth());
    } else if(align == 'center') {
      x -= target.outerWidth() / 2 - element.outerWidth() / 2;

      position: 'absolute',
      zIndex:   5000,
      top:      y, 
      left:     x



Normally you would use this code within an event listener such as mouseover or click:

$(".add-link").live('click', function(event) {
      var target = $(this);
      var dialog = $('#add-link-dialog');

      dialog.positionOn(target, 'center');;

      return false;

More examples:

# Default is align with top left corner of given element
# But you can align to the right and center
$('#add-link-dialog').positionOn($('.add-link'), 'right')
$('#add-link-dialog').positionOn($('.add-link'), 'center')

You'll need the jQuery dimensions plugin for this to work.

How to build popup menus and tooltips with jQuery

Tagged menu, hover, tooltip, contextmenu, jquery, popup  Languages javascript

This snippet shows you how to build a simple popup menu with jQuery. The example code can also be used to build things such as tooltips.

In the example we're going to build a menu for deleting table rows.


<table id="data">
      <a href='/domains/'></a>
      <!-- menu start -->
      <span class='hover-menu'>
        <a href='/domains/' class='remove'>remove</a>
      <!-- menu end -->

The CSS:

  display: none

The Javascript:

$.event.special.hover.delay = 200; 
$.event.special.hover.speed = 200; 

var show = function(e) {
  var $this = $(this);
  var $tooltip = $this.find('.hover-menu');

var hide = function() {
  var $this = $(this);
  var $tooltip = $this.find('.hover-menu');
$('#data td').bind('hover', show);
$('#data td').bind('hoverend', hide);

When you hover your mouse over table rows the menu will be shown.

You'll need to install the Event hover jQuery plugin to be able to use the hover and hoverend events. You could replace them with mouseenter and mouseleave, but usability would suffer...