Building a WYSIWYG HTML Editor Part 1/2 - Building our HTML editor (contd.) (Page 6 of 7 )
Now that we've covered all of the controls, letís look at how we can change the font and size of the text in our document. The three dropdown lists at the bottom of our HTML editor can be used to change the font, change the fonts size, and format text using a header style.
If we have selected some text in our document, then only that text's font will change. If we haven't selected any text, then any text that we type in after selecting the new font will appear as the selected font.
The fName argument of the doFont() function is the value of the currently selected font, and is retrieved in the dropdown lists onClick handler:
As you can see, we pass the "formatblock" command to execCommand, and set the value argument to the heading type, which is the value of the currently selected option for the heading dropdown list. After the call to execCommand, the type of font for the selected text reverts back to the default, so we have to set it again. That's why we call doFont.
var viewMode = 1; // WYSIWYG
// Other code exists here
if(viewMode == 1)
iHTML = iView.document.body.innerHTML;
iView.document.body.innerText = iHTML;
// Hide all controls
tblCtrls.style.display = 'none';
selFont.style.display = 'none';
selSize.style.display = 'none';
selHeading.style.display = 'none';
viewMode = 2; // Code
iText = iView.document.body.innerText;
iView.document.body.innerHTML = iText;
// Show all controls
tblCtrls.style.display = 'inline';
selFont.style.display = 'inline';
selSize.style.display = 'inline';
selHeading.style.display = 'inline';
viewMode = 1; // WYSIWYG
To show the source code of our document, we grab the inline frame's HTML from using the iView.document.body.innerHTML variable. We then set the innerText property of the inline frame to this value, which in turns causes its HTML code to be displayed. We also hide our HTML editors buttons and dropdown lists using display = 'inline'.
Our HTML editor before toggling:
Our HTML editor after toggling: