Insert HTML programmatically in wysiHTML5 editor
Asked Answered
F

3

9

I found javascript wysiwyg editor wysiHTML5.

I'm trying to add element <a href=...> to the editor or just turn on bold programmatically.

My code is:

var editor = new wysihtml5.Editor("textarea", {
    toolbar:      "toolbar",
    stylesheets:  "css/wysihtml5.css",
    parserRules:  wysihtml5ParserRules
});

editor.observe("load", function() {
    editor.composer.commands.exec("bold");
});

Am I doing something wrong?

Fussy answered 24/5, 2012 at 14:13 Comment(0)
T
15

Actually no, but you have to be sure that your textarea (iframe) is focused. Try to use on instead of observe. Here is a sample code that worked for me with insertHTML.

editor.on("load", function() {
  editor.focus();
  editor.composer.commands.exec("insertHTML","<a href=....>text</a>");
});
Tampa answered 27/5, 2012 at 1:8 Comment(5)
Thanks! I spent a couple of hours trying to figure this out, it should really be in the docsHigdon
If you don't mind erasing the html in the editor you can use the setValue command i.e editor.setValue("<a href=...>");Emperor
Please note your colon at the end of the script. Should it be a semicolon?Townsley
Added semicolon, I was in too hurry to read comment and spent half hour to notice thatForjudge
This worked very well for me. But how do I blur/unfocus the editor after the "insertHTML" insertion? I have tried a few things, amongst other editor.blur() but nothing seems to work.Pali
B
8

mateusmaso's solution gave me the following error:

NS_ERROR_FAILURE: Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsIDOMHTMLDocument.execCommand]
[Break On This Error]   

Object.defineProperty(object, property, config);

So I've investigated some more and found the following solution, which (IMO) seems more ok:


var value = 'whatever you want to set';
// The jQuery reference to the textarea
var $ta = $('textarea#your-selector');
// The reference to the wysihtml5 editor - everything is contained within it 
var w5ref = $ta.data('wysihtml5');
// Check if you have it
if(w5ref){
   // if yes it's really an enhanced / wysihtml5ed textarea 
   // and use its setter
   w5ref.editor.setValue(value);
} else {
   // otherwise just simply populate the textarea as you normally would
   $ta.html(value);
}

Source

Brotherinlaw answered 13/12, 2012 at 21:16 Comment(0)
M
2

assuming you have instantiated the editor previously using $('#textarea-id').wysihtml5()

$('#textarea-id').data("wysihtml5").editor.setValue('new content');

font

Mensal answered 13/10, 2016 at 17:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.