openWYSIWYG with Dynamic Content

If you're trying to use openWYSIWYG with a textarea control that was dynamically added to your DOM via an Ajax call or other JS code, then you may be baffled as to why nothing happens.

That's because openWYSIWYG configures itself to initialize after the window.load event gets triggered. When using it dynamically however, the window.load event is long gone, so it'll just sit there waiting forever.

If using jQuery, the easy fix for this is to hack the wysiwyg.js source file and do the following replacements:

  • Line 357: WYSIWYG_Core.addEvent(window, "load", function generateEditor() {WYSIWYG._generate(id, settings);}); 
  • Replace with: $(document).ready(function(){WYSIWYG._generate(id, settings);});

  • Line 360: WYSIWYG_Core.addEvent(window, "load", function generateEditor() {WYSIWYG.attachAll(settings);});
  • Replace with: $(document).ready(function(){WYSIWYG.attachAll(settings);});

  • Line 391: WYSIWYG_Core.addEvent(window, "load", function displayIframe() {WYSIWYG._display(id, settings);});
  • Replace with: $(document).ready(function(){WYSIWYG._display(id, settings);});

  • Line 394: WYSIWYG_Core.addEvent(window, "load", function displayIframe() {WYSIWYG.displayAll(settings);});
  • Replace with: $(document).ready(function(){WYSIWYG.displayAll(settings);});


This basically tells openWYSIWYG to initialize whenever the document is ready after the call is made, instead of waiting for windows.load.

NOTE: For this to work, you first need to resolve the openWYSIWYG and jQuery conflict. You can download the edited wysiwyg.js file directly to save you making the edits (based on version 1.4.7).

UPDATE: Another problem with openWYSIWYG is that it hides the original textarea and inserts an iframe which is used to enter the text/HTML. The original textarea is only updated with the new text when submitting a form. In my case however, I use a custom Ajax handler to call backend services, which means the form submit event never gets triggered, and hence the textarea value does not reflect the iframe value. You could hack your Ajax code to hunt for the corresponding iframe and use that value instead, but I thought it would be cleaner to just hack wysiwyg.js to always keep the textarea value in sync with the iframe content. To do this you need to insert a few WYSIWYG.updateTextArea(n); calls and bind them to keyup/mouseout/blur events on the iframe. You also need to add the call at the end of the two execCommand functions (applying stuff from the toolbar). If you want this functionality, feel free to use this version.


Comments

Popular posts from this blog

Wkhtmltopdf font and sizing issues

Import Google Contacts to Nokia PC Suite

Can't delete last blank page from Word