Recommended books

Positioning an element over another element with jQuery

JavaScript posted about 1 year ago by christian

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:

   1  $.fn.positionOn = function(element, align) {
   2    return this.each(function() {
   3      var target   = $(this);
   4      var position = element.position();
   5  
   6      var x      = position.left; 
   7      var y      = position.top;
   8  
   9      if(align == 'right') {
  10        x -= (target.outerWidth() - element.outerWidth());
  11      } else if(align == 'center') {
  12        x -= target.outerWidth() / 2 - element.outerWidth() / 2;
  13      }
  14  
  15      target.css({
  16        position: 'absolute',
  17        zIndex:   5000,
  18        top:      y, 
  19        left:     x
  20      });
  21    });
  22  };
  23  

Usage:

   1  $('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:

   1  $(".add-link").live('click', function(event) {
   2        var target = $(this);
   3        var dialog = $('#add-link-dialog');
   4  
   5        dialog.positionOn(target, 'center');
   6        dialog.show();
   7  
   8        return false;
   9      });  

More examples:

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

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

Tagged jquery, position, absolute, tooltip, dialog