position 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;

      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 find a Google Map marker's exact position

Tagged position, relative, google-maps, marker  Languages javascript

You need a custom OverlayWindow:

function ProjectionHelperOverlay(map) {

ProjectionHelperOverlay.prototype = new google.maps.OverlayView();
ProjectionHelperOverlay.prototype.draw = function () {
  if (!this.ready) {
    this.ready = true;
    google.maps.event.trigger(this, 'ready');

overlay = new ProjectionHelperOverlay(map);

And you need to find the markers position relative to the overlay:

google.maps.event.addListener(marker, 'mouseover', function(event) {
  var p = overlay.get_projection().fromLatLngToDivPixel(marker.get_position());

  // map world relative to map container
  var container = overlay.get_panes().mapPane.parentNode;
  var x = p.x + parseInt(container.style.left);
  var y = p.y + parseInt(container.style.top);

Code found in this thread on Google Groups.