2

I have a javascript: bookmarklet with the code

javascript:document.body.contentEditable = !document.body.contentEditable; 

which should switch on and off an "editor" for the page (just for pranks on friends and such). But it does not acheive the desired outcome, nothing happens when I click the bookmark. Opening up the Javascript Console, I see that:

document.body.contentEditable
  "false"
!document.body.contentEditable
  false

Previously, I used javascript:document.body.contentEditable = true; and this makes the page editable but I cannot turn it off.

Griffin Young
  • 223
  • 1
  • 4
  • 11

5 Answers5

9

Like you probably noticed in the JavaScript Console, document.body.contentEditable is a String, not a Boolean. You can do this instead:

document.body.contentEditable = !(document.body.contentEditable == "true");

or just

document.body.contentEditable = document.body.contentEditable != "true";

The HTMLElement.contentEditable property is used to indicate whether or not the element is editable. This enumerated attribute can have the following values:

  • "true" indicates that the element is contenteditable.
  • "false" indicates that the element cannot be edited.
  • "inherit" indicates that the element inherits its parent's editable status.

https://developer.mozilla.org/en/docs/Web/API/HTMLElement/contentEditable

Dogbert
  • 212,659
  • 41
  • 396
  • 397
1

document.body.contentEditable is a string value and JavaScript considers non-empty strings to be truthy.

!"" == true
!"a" == false
Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74
0

The value of contentEditable is a string, not a boolean. It can have the values "true", "false" or "inherit" (therefore it can't be a simple boolean). A boolean inversion won't work. You need to explicitly assign one of these three strings.

deceze
  • 510,633
  • 85
  • 743
  • 889
0

Is contentEditable a text input? So you need to parse the texto into boolean:

javascript:document.body.contentEditable = !JSON.parse(document.body.contentEditable); 
Diego Polido Santana
  • 1,425
  • 11
  • 19
0

deceze is correct here, I (somewhat stupidly) thought that because you do document.body.contentEditable = true;
you could also do
!document.body.contentEditable; but this is not correct.

In the end, I decided to use the property that is actually a boolean, isContentEditable, like so:
document.body.contentEditable = !document.body.isContentEditable;

Griffin Young
  • 223
  • 1
  • 4
  • 11