Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to position a popup div based on the position of where the cursor clicks

Tags:

jquery

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

like image 641
some_bloody_fool Avatar asked Feb 09 '12 22:02

some_bloody_fool


2 Answers

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.

like image 99
mrtsherman Avatar answered Oct 29 '22 20:10

mrtsherman


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.

like image 25
Gigi Avatar answered Oct 29 '22 20:10

Gigi