Reputation: 9084
I am trying to create a edit and delete option for a list of items for which i have made it display when user right click on that list item.
document.addEventListener('contextmenu', function(e) {
e.preventDefault();
var x = e.offsetX;
var y = e.offsetY;
var d = document.getElementById("context-menu");
d.style.display = "block";
d.style.left = x + 'px';
d.style.top = y + 'px';
console.log(x, y);
}, false);
#context-menu {
display: none;
position: absolute;
color: blue;
}
.listItems li {
padding-bottom: 25px;
}
<ul class="listItems">
<li>I am list one</li>
<li>I am list two</li>
<li>I am list three</li>
<li>I am list four</li>
</ul>
<ul id="context-menu">
<li> Edit </li>
<li> Delete </li>
</ul>
And the jsfiddle link was, https://jsfiddle.net/dmfvz5qw/1/
Here when i make a right click, the id named context-menu
is not displaying nearby the mouse arrow and it is showing at more top of the clicked list.
I am in the need to display the context-menu
nearby right clicked position rather than any other position.
Kindly help me to fix the issue and also i am in the need of result in Pure Javascript.
Upvotes: 1
Views: 1764
Reputation: 13801
You need to use clientX and clientY here,
If you want to learn more about the positioning using body scroll position too, then refer this link https://stackoverflow.com/a/7790764/2630817
document.addEventListener('contextmenu', function(e) {
e.preventDefault();
document.getElementById("context-menu").display = 'none';
var x = e.clientX ;
var y = e.clientY;
var d = document.getElementById("context-menu");
d.style.display = "block";
d.style.left = x+'px';
d.style.top = y+'px';
console.log(x,y);
}, false);
#context-menu {
display: none;
position: absolute;
color: blue;
padding: 0;
width:50px;
}
<ul class="listItems">
<li>I am list one</li>
<li>I am list two</li>
<li>I am list three</li>
<li>I am list four</li>
</ul>
<ul id="context-menu">
<li> Edit </li>
<li> Delete </li>
</ul>
Upvotes: 1
Reputation: 3205
Please use clientX
and clientY
instead:
var x = e.clientX;
var y = e.clientY;
Upvotes: 2