How to clear the contents of the openwysiwyg editor? - javascript

I am using the openwysiwyg editor in my webpage. I want to clear the contents of it. I have used
$('#report').val('');
but that doesn't clear it.
The editor creates an iframe and updates the contents there, syncing as it goes.
How would I go about clearing it?

You probably need to supply a bit more information - the html itself would be very useful, but I'm going to assume that report is the id of the textarea you need cleared.
If it's a normal textarea, your code should really work.
If (as Paulo mentions in the comments) it's being modified by an openwysiwyg editor, it's probably being turned into an iFrame with it's own HTML page in it. It's a lot more difficult to manipulate the iFrame.
Looks like that's the case.
Have a look at this example to see if it helps you reference the iFrame itself: http://www.bennadel.com/index.cfm?dax=blog:1592.view
This is a hacked excerpt of the example.html that comes with openwysiwyg:
<script type="text/javascript">
// Use it to attach the editor to all textareas with full featured setup
//WYSIWYG.attach('all', full);
// Use it to attach the editor directly to a defined textarea
WYSIWYG.attach('textarea1'); // default setup
WYSIWYG.attach('textarea2', full); // full featured setup
WYSIWYG.attach('textarea3', small); // small setup
// Use it to display an iframes instead of a textareas
//WYSIWYG.display('all', full);
function getIFrameDocument( id )
{
var iframe = document.getElementById(id);
if (iframe.contentDocument) {
// For NS6
return iframe.contentDocument;
} else if (iframe.contentWindow) {
// For IE5.5 and IE6
return iframe.contentWindow.document;
} else if (iframe.document) {
// For IE5
return iframe.document;
} else {
return null;
}
}
function clearcontents()
{
getIFrameDocument('wysiwygtextarea1').body.innerHTML = '';
}
</script>
Then somewhere in the page, I've got a clear button (actually div):
<div style="width:120px;height:20px;background:#ff0000;text-align:center;display:block;" onclick="clearcontents();">Clear!</div>
Note that the id of your textarea is prefixed with wysiwyg. That's the name of the iFrame.
I've tested this in Firefox but nothing else at the moment. The code for getting the iFrame I found on the Net somewhere, so hopefully it works for other browsers :)

This works, but is butt ugly:
var frame = WYSIWYG.getEditor('--ENTER EDITOR NAME HERE--');
var doc = frame.contentWindow.document;
var $body = $('html',doc);
$body.html('');
Replace --ENTER EDITOR NAME HERE-- by whatever you pass to the editor when you call attach.

I believe this works
$('#report').text('');

Related

addEventListener to div element

I am trying to fire a script when the contents of a div are altered, specifically when a div receives the next set of results from a js loaded paginator.
I have this:
<script script type="text/javascript" language="javascript">
document.addEventListener("DOMCharacterDataModified", ssdOnloadEvents, false);
function ssdOnloadEvents (evt) {
var jsInitChecktimer = setInterval (checkForJS_Finish, 111);
function checkForJS_Finish () {
if ( document.querySelector ("#tester")
) {
clearInterval (jsInitChecktimer);
//do the actual work
var reqs = document.getElementById('requests');
var reqVal = reqs.get('value');
var buttons = $$('.clicker');
Array.each(buttons, function(va, index){
alert(va.get('value'));
});
}
}
}
</script>
This works well when the doc loads (as the results take a few seconds to arrive) but I need to narrow this down to the actual div contents, so other changes on the page do not fire the events.
I have tried:
var textNode = document.getElementById("sitepage_content_content");
textNode.addEventListener("DOMCharacterDataModified", function(evt) {
alert("Text changed");
}, false);
But the above does not return anything.
Can what I am trying to do be done in this way? If yes where am I going wrong?
Using Social Engine (Zend) framework with MooTools.
I did this in the end with a little cheat :-(
There is a google map loading on the page that sets markers to match the location of the results. So I added my events to the end this code namely: function setMarker() {}.
I will not mark this as the correct answer as it is not really an answer to my question, but rather a solution to my problem, which is localised to the Social engine framework.
I will add a Social engine tag to my original question in the hope it may help someone else in the future.
Thanks guys.

Convert contenteditable div's content to plaintext via javascript

I'm trying to make custom lightweight rich text editor with just one feature - adding links. I did some research and desided iframe is the best choice. After some messing around it works with one exception - I need to run some code on keyup event. I read everything I found on the internet and nothing helped, still doesn't work...
iframe.document.designMode = 'On';
iframe.document.open();
iframe.document.write(someHTML);
iframe.document.close();
var keyupHandle = function() { /* some code */ };
var iframeDoc = document.getElementById('iframe').contentWindow.document;
if(iframeDoc.addEventListener) {
iframeDoc.addEventListener('keyup', keyupHandle(), true);
} else {
iframeDoc.attachEvent('onkeyup', keyupHandle());
}
I think I remember needing to wait for the iframe to fully load before adding event handlers to the document. If possible, add something to the iframe's HTML to call out to the parent page when it's loaded:
window.iframeLoaded = function() {
var iframeDoc = document.getElementById('iframe').contentWindow.document;
if(iframeDoc.addEventListener) {
iframeDoc.addEventListener('keyup', keyupHandle(), true);
} else {
iframeDoc.attachEvent('onkeyup', keyupHandle());
}
};
iframe.document.designMode = 'on';
iframe.document.open();
iframe.document.write('<html><body onload="parent.iframeLoaded()">Stuff</body></html>');
iframe.document.close();
Failing that, setting a brief timer using window.setTimeout() will probably work.

Is there something like simple_html_dom.php for JavaScript?

I'm building an iPhone app using Appcelerator Titanium, and I need to convert a HTML string (which may contain invalid HTML like missing tags, not my fault) to a DOM object. In this DOM element I need to find a specific <div>, and put the contents of this <div> in a WebView.
Anyway, I am looking for something like the Simple HTML DOM script, which is for PHP, to search through the DOM for this <div>. I'd like the script to scan the (invalid) HTML string, and get the innerHTML of the <div>.
How can I best do this in JavaScript?
The code below is the basic string-to-DOM convertor. See the linked answer for a detailed explanation.
function string2dom(html, callback){
/* Create an IFrame */
var iframe = document.createElement("iframe");
iframe.style.display = "none";
document.body.appendChild(iframe);
var doc = iframe.contentDocument || iframe.contentWindow.document;
doc.open();
doc.write(html);
doc.close();
function destroy(){
iframe.parentNode.removeChild(iframe);
}
if(callback) callback(doc, destroy);
else return {"doc": doc, "destroy": destroy};
}
This code snippet does not sanitise the HTML. Scripts will be executed, external sources will be loaded. The explanation of the code, and HTML sanitiser can be found at this answer
Usage (examples), Fiddle: http://jsfiddle.net/JFSKe/:
string2dom("<html><head><title>Test</title></head></html>", function(doc, destroy){
alert(doc.title); /* Alert: "Test" */
destroy();
});
var test = string2dom("<div id='secret'></div>");
alert(test.doc.getElementById("secret").tagName); /* Alert: "DIV" */
test.destroy();

jquery thickbox reference problem

Completely restated my question:
Problem: Losing reference to an iFrame with Mozilla firefox 3.6 and 4.0
More info:
- Works fine in internet explorer 8 64-bit and 32-bit version.
How to reproduce? In Mozilla: Open the editor accordion menu. Click the 'editor openen' link, in the editor fill in some random text, then click 'bestand opslaan'. Fill in a name and click on 'save'. The content of the editor will be downloaded in HTML format.
Close the save file dialog box by clickin outside of it or on the specified buttons. Click on the 'bestand opslaan' button again and try to save your content to a file. You'll see nothing happening.
The problem isn't there in IE8. Try opening it in there.
Firebug tells me this the second time you open the save dialog:
iFrame.document is null
Example Link: http://www.newsletter.c-tz.nl/
More info:
- switched from thickbox to colorbox to try and resolve this issue and because thickbox isn't supported for a long time now.
- colorbox gives me the same problem so I don't think it is this.
- tried googling for iframe reference error and like, found nothing.
- tried putting the iframe code outside of the div that is called by the colorbox script, it retains it reference but not when I put it back inside that div.
Thanks to: JohnP who offered to open a 'hunt' on this.
Edit:
I thought maybe the saveFile.php file was causing trouble to the parent of the iframe but after removing it from the action variable in the editor.php script it still fails with the same error after you open the dialog for a second time.
Can someone maybe write a script that iterates through iframes by name and when the rignt iframe is found reference it to a var? I want to try it but don't know how..
I can't explain why it's work the first time for Firefox, but in Firefox the function to used for get iframe is different of IE : How to get the body's content of an iframe in Javascript?.
So, replace your JavaScript function "saveToFile" to this :
function saveToFile() {
var saveAsFileName = document.getElementById('saveAs_filename').value;
var currentContent = tinyMCE.editors["editor_textarea"].getContent();
var editorFileName = document.getElementById('editor_filename');
var iFrameTag = document.getElementById('saveAs_Iframe');
var iFrame;
if ( iFrameTag.contentDocument )
{ // FF
iFrame = iFrameTag.contentDocument;
}
else if ( iFrame.contentWindow )
{ // IE
iFrame = iFrameTag.contentWindow.document;
}
var inframeEditorFileName = iFrame.getElementById('editor_filename');
var inframeEditorContent = iFrame.getElementById('editor_textarea');
editorFileName.value = saveAsFileName;
inframeEditorFileName.value = saveAsFileName;
inframeEditorContent.value = currentContent;
iFrame.editor_self.submit();
}
I replace the function with Firebug and it's works for me.
Update :
You can also used a crossbrowser solution, more simple, thanks to jQuery :
function saveToFile() {
var saveAsFileName = document.getElementById('saveAs_filename').value;
var currentContent = tinyMCE.editors["editor_textarea"].getContent();
var editorFileName = document.getElementById('editor_filename');
editorFileName.value = saveAsFileName;
$("#saveAs_Iframe").contents().find("#editor_filename").val(saveAsFileName)
$("#saveAs_Iframe").contents().find("#editor_textarea").val(currentContent)
$("#saveAs_Iframe").contents().find("form[name=editor_self]").submit();
}

How to append div tag dynamically in html using javascript/

I am creating one div dynamically and want to add it inside another div.
(js) var divtag = document.createElement("div");
divtag.innerHTML = xmlhttp.responseText;//Ajax call working fine
document.getElementById('con').appendChild(divtag);
html:
enter code here <div id="con"></div>
The the o/p I am getting from AJAX call is Ok, also i am able to view it in browser, but when I am doing a view source I am unable to see the div and its contents.
It should come as :
enter code here <div id="con">
<div>
Contents added # runtime
</div>
</div>
Can somebody suggest where I am going wrong?
You won't see the generated code in the browser by default, but you can use the Firefox extension Web Developer to view the code generated after executing js.
-- edit
also helpful extension for FF - FireBug.
Use firebug - the best firefox web development addon in my opinion.
With firebug you can inspect the DOM:
(source: mozilla.org)
Do you have "con" div loaded on our DOM?
var divtag = document.createElement("div");
divtag.innerHTML = xmlhttp.responseText;//Ajax call working fine
// See before adding a child, does it exist?
alert(document.getElementById('con'));
document.getElementById('con').appendChild(divtag);
I don't know where you having this code. As it is important that the DOM should be loaded before checking/assigning anything to an element. To avoid such a mistake:
function addEvent(obj, evType, fn){
if (obj.addEventListener){
obj.addEventListener(evType, fn, false);
return true;
} else if (obj.attachEvent){
var r = obj.attachEvent("on"+evType, fn);
return r;
} else {
return false;
}
}
addEvent(window, 'load', function() {
var divtag = document.createElement("div");
divtag.innerHTML = xmlhttp.responseText;//Ajax call working fine
// See before adding a child, does it exist?
alert(document.getElementById('con'));
document.getElementById('con').appendChild(divtag);
});

Categories