Could you please tell me why the div not appearing right where I click? It appears on top-left only.
CSS:
#palette {
display: none;
width: 20px;
height: 20px;
background-color: red;
}
HTML:
<div id="palette"></div>
Javascript:
window.addEventListener('contextmenu', function(ev) {
ev.preventDefault();
document.getElementById('palette').setAttribute('left', ev.pageX);
document.getElementById('palette').setAttribute('top', ev.pageY);
document.getElementById('palette').setAttribute('position', 'absolute');
document.getElementById('palette').style.display = 'block';
return false;
}, false);
Here's the fiddle:
https://jsfiddle.net/0rL9neeL/
EDIT: Sorry, seems like I haven't explained an issue: Yes, it is the right click. That's where the div
should appear.
You can get the coordinates using
ev.clientX
,ev.clientY
for example(which returns the coordinates relative to the viewport in CSS pixels), and then just set the styles with javascript. You can do it this way:The problem with your code was that you were using
setAttribute
which sets atributtes to DOM elements, and not inline CSS.