I am developing a wysiwyg HTML editor using javascript and an editable iframe. Prior to developing the editor, I did some research into other HTML editors that use javascript and iframes (including CKEditor), and there is one feature that I am struggling to duplicate.
In some iframe/JS-based HTML editors, if a user wishes to access or edit an element’s attributes (e.g. image dimensions, hyperlink url, table width), they can simply double click the element and a modal div will appear with text boxes containing the attribute values of that element and/or those of the elements within that element.
So far, the closest that I have came to developing a feature like this was to create a script that alerts the HTML code of an area within the iframe that the user double clicks on. I added this code to my HTML page;
<iframe name="wysiwyg" id="wysiwyg" onload="dblClick();"></iframe>
and added this code to my javascript file;
function dblClick(){
document.getElementById("wysiwyg").contentWindow.document.ondblclick=dblClicked;
window.frames["wysiwyg"].document.body.ondblclick=dblClicked;
}
function dblClicked (){
txt = wysiwyg.document.selection.createRange().htmlText;
alert(txt);
}
The problem is that this code only works when a user double clicks and highlights a section of text, for example, double clicking a selection of bold text would alert this piece of code to the user;
<b>text</b>
Anything else that I double click on alerts an error message. Furthermore, it only works properly in Internet Explorer. When I tested it in Firefox, Opera, Chrome, and Safari, the script either did not work or did not work properly (in Firefox, the script alerted error messages as soon as the page was loaded).
What I need is a script that allows the end user to view all the properties of any element they double click on within the editable iframe and works in all major browsers.
I know it would be easier to simply use an existing wysiwyg editor, but I prefer to create my own from scratch as I enjoy the challenge. Also, I know CKEditor does not appear to use iframes like mine, but I am referencing it as an example of the sort of functionality that I wish to achieve.
Any help would be appreciated.
There are various problems/misunderstandings here:
TextRangeAPI, which is not supported in other browsers;dblclickhandler twice, unnecessarily.I’d suggest skipping the selection stuff and using event delegation to get the element that was double clicked, which will work in all major browsers.