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      = position.top;

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

    target.css({
      position: 'absolute',
      zIndex:   5000,
      top:      y, 
      left:     x
    });
  });
};

Usage:

$('selector-for-elements-to-position').positionOn($('selector-for-element-to-position-them-on'))

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');
      dialog.show();

      return false;
    });

More examples:

# Default is align with top left corner of given element
$('#add-link-dialog').positionOn($('.add-link'))
# 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.

The HTML:

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

The CSS:

.hover-menu
  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');
  $tooltip.fadeIn();
}

var hide = function() {
  var $this = $(this);
  var $tooltip = $this.find('.hover-menu');
  $tooltip.fadeOut();
}
$('#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...