I have a canvas element in my HTML document. When I click inside of the canvas multiple times, it selects part of my <h1>
element's text, which is before the <canvas>
tag. Is there a way to stop this from happening? I am guessing there is a JavaScript solution.
Asked
Active
Viewed 3,430 times
6
2 Answers
15
Returning false
in an event stops the standard event from happening:
document.getElementById('canvas').onmousedown = function(){
return false;
};
Edit: I just found out that text selection is done before onclick
is fired, a better option is onmousedown
.

Harmen
- 22,092
- 4
- 54
- 76
-
Here's how you do it in jQuery: `$("#canvas").on("mousedown", function () { return false; });` – Semmel Mar 09 '17 at 19:38
1
If you want to use the mousedown
event to do other things, you can prevent only text selection more specifically by setting the onselectstart
event to return false
.
//give your canvas an id, I used 'can'
var canvas = document.getElementById('can');
canvas.onselectstart = function () { return false; }

Simon Sarris
- 62,212
- 13
- 141
- 171