9

I am trying to position a popup div below:

<div style="display:none;height:200px;width:200px;border:3px solid green;" id="popup">Hi</div>

based on the clicking of another div.

I am running this on document .ready

$('div#d').bind('click', function (event) {
var offset = $(this).offset();
$('#popup').css('left',offset.left);    
$('#popup').css('top',offset.top);
$('#popup').css('display','inline');        
});

but the above will not even display the div

some_bloody_fool
  • 4,605
  • 14
  • 37
  • 46

2 Answers2

17

The problem lie in the fact that offset() do not return the correct mouse position, try event.pageX and event.pageY instead:

$(document).ready(function(){
    $('div#d').bind('click', function (event) {
    $('#popup').css('left',event.pageX);      // <<< use pageX and pageY
    $('#popup').css('top',event.pageY);
    $('#popup').css('display','inline');     
    $("#popup").css("position", "absolute");  // <<< also make it absolute!
    });
});

See here.

Gigi
  • 4,953
  • 24
  • 25
  • 1
    If the containing element is position:absolute or relative, positioning the popup absolutely causes it to appear relative to the container, not the page. – Stephen Corwin Jun 14 '13 at 01:52
  • 2
    For easy reference and improvements, here's the jsFiddle: https://jsfiddle.net/hwsamuel/fsp5pgqw/ – Hamman Samuel Apr 01 '16 at 17:19
3

Try adding position: absolute to your div. Make sure it isn't located within another div that has relative positioning.

<div style="position: absolute; display:none;height:200px;width:200px;border:3px solid green;" id="popup">Hi</div>

Top and left only work for elements with relative, absolute or fixed positioning.

mrtsherman
  • 39,342
  • 23
  • 87
  • 111
  • that is working well for displaying the div,thank you, but it is not positioning the div where the cursor clicked – some_bloody_fool Feb 09 '12 at 22:56
  • Did you make sure that div isn't inside something else that has relative positioning? Try making it the very first or very last item in your body. – mrtsherman Feb 09 '12 at 22:59