How to place a popup div based on the position at which the cursor clicks

I am trying to position the popup below:

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

based on the click of another div.

I run this on a .ready document

 $('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 div will not be displayed above

+6
source share
2 answers

The problem is that offset () will 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 .

+16
source

Try adding position: absolute to your div. Make sure it is not in another div that has relative positioning.

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

At the top and left, only elements with relative , absolute or fixed positions work.

+1
source

Source: https://habr.com/ru/post/908103/


All Articles