I’ve been trying to create a custom context menu with some buttons in it, however there is a problem. I have an opacity transition, and it only runs once when I right click. The next times I right click the menu will show up but without the opacity transition.
Here is my code:
HTML:
<div id="contextMenuDesktop">
<ul>
<!-- Some elements here -->
</ul>
</div>
JavaScript:
document.addEventListener('contextmenu', function(e) {
event.preventDefault();
if(!menuOpened) {
document.getElementById("contextMenuDesktop").style.opacity = "0";
setInterval(function() {
document.getElementById("contextMenuDesktop").style.opacity = "1";
}, 100); // It has to be run few milliseconds after, for some reason
document.getElementById("contextMenuDesktop").style.display = "block";
document.getElementById("contextMenuDesktop").style.left = `${e.pageX}px`;
document.getElementById("contextMenuDesktop").style.top = `${e.pageY}px`;
}});
CSS:
#contextMenuDesktop {
transition: opacity 500ms;
opacity: 0;
height: 375px;
width: 175px;
background-color: rgba(100,100,100,.6);
color: white;
border-radius: 10px;
box-shadow: 7px 7px 3px lightgray;
backdrop-filter: blur(5px);
position: fixed;
z-index: 3;
display: none;
}
I believe the problem is that the line that sets the opacity to 0 doesn’t have time to finish, and after only 100 milliseconds it has to be visible again, so the transition doesn’t work. Does somebody know the answer?