Open JavaScript bootstrap drop-down menu at mouse position

I want my dropdown menus to be loaded in the mouse position. For some reason, pages X and pageY are wrong. To fix this, I have to add or subtract from x and y. BUT, if I then zoom in or out, X and Y will again be erroneous. I tried everything. This is one of them.

Html:

<div class="dropdown"> <div id="menuitems" onclick="setposition(event)" class="dropdown-toggle" data-toggle="dropdown"> Menu </div> <ul class="dropdown-menu" id="xxx" role="menu" aria-labelledby="menuitems"> <li role="presentation"><a role="menuitem" tabindex="-1" href="#"</i>Link 1</a></li> <li role="presentation"><a role="menuitem" tabindex="-1" href="#"</i>Link 2</a></li> </ul> </div> 

Script

 function setposition(e) { var bodyOffsets = document.body.getBoundingClientRect(); tempX = e.pageX - bodyOffsets.left; tempY = e.pageY; $("#xxx").css({ 'top': tempY, 'left': tempX }); } 

What do I need to do to get the correct X and Y position with different resolutions?

thanks

+5
source share
1 answer

It seems that the event was not called

It works:

Bootply : http://www.bootply.com/pEFhaLWTht

Js

 function setposition(e) { var bodyOffsets = document.body.getBoundingClientRect(); tempX = e.pageX - bodyOffsets.left; tempY = e.pageY; console.log(tempX); $("#xxx").css({ 'top': tempY, 'left': tempX }); } $('#menuitems').on('click', function(e){ setposition(e); }); 

HTML

 <div class="dropdown"> <div id="menuitems" class="dropdown-toggle" data-toggle="dropdown"> Menu </div> <ul class="dropdown-menu" id="xxx" role="menu" aria-labelledby="menuitems"> <li role="presentation"><a role="menuitem" tabindex="-1" href="#" <="" i="">Link 1</a></li> <li role="presentation"><a role="menuitem" tabindex="-1" href="#" <="" i="">Link 2</a></li> </ul> </div> 
+3
source

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


All Articles