Popover on mouse click

Opens a popover in the position the user clicked preventing the dialog to go outside the body.

HTML

<img class="Img" alt="Mapa" src="http://www.webmastergrade.com/wp-content/uploads/2009/09/Amazing-Dolphin.jpg">
<div class="popover">
  <input type='text' class='span1' />
  <input type='button' class='btn' value='Save' />
</div>

CSS

body {
  margin: 0;
  padding: 0;
  overflow: hidden
}

img {
  width: 100%;
  height: auto
}

.popover {
  position: absolute;
  display: none;
  background: #fff;
  border: 1px solid #999;
  padding: 10px;
  width: auto;
  box-shadow: 0 0 10px rgba(0, 0, 0, .5);
}

.popover:after,
.popover:before {
  right: 100%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}

.popover:after {
  border-color: rgba(255, 255, 255, 0);
  border-right-color: #ffffff;
  border-width: 10px;
  top: 50%;
  margin-top: -10px;
}

.popover:before {
  border-color: rgba(201, 201, 201, 0);
  border-right-color: #c9c9c9;
  border-width: 11px;
  top: 50%;
  margin-top: -11px;
}

.popover.opposite:after,
.popover.opposite:before {
  right: auto;
  left: 100%;
}

.popover.opposite:after {
  border-color: rgba(255, 255, 255, 0);
  border-left-color: #ffffff;
}

.popover.opposite:before {
  border-color: rgba(201, 201, 201, 0);
  border-left-color: #c9c9c9;
}

JavaScript

$('.Img').click(function(e) {
  var offset = $(this).offset();
  var left = e.pageX;
  var top = e.pageY;
  var theHeight = $('.popover').height();
  var theWidth = $('.popover').width();
  var stageWidth = $(window).width();
  $('.popover').removeClass('opposite');
  if (stageWidth - left < theWidth) {
    $('.popover').css('left', (left - (theWidth) - 30) + 'px');
    $('.popover').addClass('opposite');
  } else {
    $('.popover').css('left', (left + 10) + 'px');
  }
  $('.popover').show();
  $('.popover').css('top', (top - (theHeight / 2) - 10) + 'px');
});