1,105,581 Community Members

contentEditable and execCommand()

Member Avatar
Octet
Posting Pro
579 posts since Nov 2011
Reputation Points: 45 [?]
Q&As Helped to Solve: 53 [?]
Skill Endorsements: 16 [?]
Featured
Sponsor
 
0
 

Helo Daniweb,

I am in the process of building a WYSIWYG text editor, in an attempt to understand how they work. I am a novice at JavaScript, however what I have learnt so far seems to make sense.

The problem comes when I try and change the text rapidly, if I change it to bold, then type something then change it to normal and repeat this a couple of times it seems to break and the text doesn't become bold until three or four clicks of the bold button later.

Could someone please explain why it does this and what sort of things I need to add to prevent it, this is my current code:

<!DOCTYPE HTML>

<html lang = "en" >

    <head>

        <title> WYSIWYG Editor </title>

        <script type = "text/javascript" >

            function WYSIWYG() {

                document.getElementById('Editor').contentDocument.designMode = "on";

            }

            function Bold() {
                document.getElementById('Editor').contentWindow.document.execCommand("bold", false, null);
            }
            function Italic() {
                document.getElementById('Editor').contentWindow.document.execCommand("italic", false, null);
            }
            function Underline() {
                document.getElementById('Editor').contentWindow.document.execCommand("underline", false, null);
            }

            function Change() {

            }

        </script>

    </head>

    <body onload = "WYSIWYG();" >

        <button onclick = "Bold()"           > <b> B </b> </button>
        <button onclick = "Italic()"         > <i> I </i> </button>
        <button onclick = "Underline()"      > <u> U </u> </button> <br><br>

        <iframe id = "Editor" ></iframe>

    </body>

</html>

Thank you.

Member Avatar
pritaeas
mod_pritaeas
11,317 posts since Jul 2006
Reputation Points: 1,420 [?]
Q&As Helped to Solve: 1,835 [?]
Skill Endorsements: 156 [?]
Moderator
Featured
Sponsor
 
0
 

document.getElementById('Editor') does a lookup each time. It would increase performance a little if you just store this in a variable once, and use the variable instead.

Member Avatar
Octet
Posting Pro
579 posts since Nov 2011
Reputation Points: 45 [?]
Q&As Helped to Solve: 53 [?]
Skill Endorsements: 16 [?]
Featured
Sponsor
 
0
 

Thank you for that tip, however the problem is that it still won't always change the text when it is pressed?

Question Answered as of 1 Year Ago by pritaeas
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article