Reputation: 36291
I have a canvas element, and in the canvas if you click a button it opens a div
modal. The modal then has some buttons on it, and if you click on one of the buttons and it is also above a button in the canvas, the canvas button also gets clicked.
I would like to disable the canvas, but I can't seem to do so. I have a tried applying css styles to the canvas
like so:
pointer-events: none
But the canvas still accepts the clicks. Is there any way for me to disable the canvas so that I can click on the modal without it affecting the canvas?
The canvas contains a game, and the game isn't always the same, so I don't have access to the canvas' code to disable the buttons in the canvas.
Upvotes: 3
Views: 17462
Reputation: 1628
First, you set it up like this:
<div class='your-canvas-wrapper'>
<canvas>
...
</canvas>
</div>
If you want to disable on page load.
.your-canvas-wrapper {
cursor: not-allowed;
pointer-events: none;
}
If you want to disable after page load, you can do this...
$(".your-canvas-wrapper").css("cursor", "not-allowed");
$(".your-canvas-wrapper").css("pointer-events", "none");
Upvotes: 5
Reputation: 8911
You can simply make a handler such as
const c = document.querySelector("#myCanvas")
c.addEventListener('click', e => {
if (c.classList.contains('disabled')) {return}
// Do not perform default action, stop bubbling the event
e.preventDefault();e.stopPropagation()
// Mark event as invalid for older browsers
return false
})
.canvas-wrapper {position:relative}
.canvas-wrapper:after {content:'';position:absolute;z-index:999;top:0;left:0;width:100%;height:100%;cursor: not-allowed; pointer-events: none}
<div class='canvas-wrapper'>
<canvas></canvas>
</div>
This creates a faux blocking element atop your canvas
element, this way it gathers all click events before they can even hit the canvas
(since the canvas is under this element)
Upvotes: 4
Reputation: 2211
Event Propagation - https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation
In the event handler for the button click, stop the propagation of the event.
Upvotes: 0