Reputation: 14204
I'm using the Summernote rich text editor in a page. I am trying do some customizations on selected text within the editor. I can successfully apply my customizations on the first item I select. However, it fails on subsequent items. I have created a Fiddle, which is available here.
The steps to reproduce my problem are:
I was expecting the word "second" to get highlighted as well and have my custom HTML attribute applied as occurred when I did it the first time. Once again, the Fiddle is here and the relevant code looks like this:
var myEditor = $('#myEditor');
$(myEditor).summernote({
height:200,
toolbar: [
['style', ['bold', 'italic', 'underline', 'clear']],
],
callbacks: {
onInit: function() {
var customButton = '<div class="note-file btn-group">' +
'<button id="myButton" type="button" class="btn btn-default btn-sm btn-small" title="My Trigger" tabindex="-1">engage</button>' +
'</div>';
$(customButton).appendTo($('.note-toolbar'));
$('#myButton').click(function(event) {
var editor = $('#myEditor');
if (editor.summernote('isEmpty') === false) {
var r = editor.summernote('createRange');
var c = editor.summernote('code');
var s1 = c.substring(0, r.so);
var s2 = '<span style="background-color:yellow;" data-tag-index="' + tags.length +'">' + r.toString() + '</span>';
tags.push(r.toString());
var s3 = c.substring(r.eo);
var modified = s1 + s2 + s3;
$('#myEditor').summernote('code', modified);
$('#results').val(modified);
}
});
}
}
});
Why doesn't this work? What am I doing wrong?
Upvotes: 4
Views: 3650
Reputation: 794
I looked up in the range for some functions in the console via console.log(r);
and I found this helpful function pasteHTML()
.
You just need to create the range via var r = editor.summernote('createRange');
and then calling r.pasteHTML()
. Then summernote automaticaly replaces the selected text by your HTML.
So my solution is this one:
var tags = [];
$(document).ready(function() {
$(function() {
$.material.init();
});
var myEditor = $('#myEditor');
$(myEditor).summernote({
height:200,
toolbar: [
['style', ['bold', 'italic', 'underline', 'clear']],
],
callbacks: {
onInit: function() {
var customButton = '<div class="note-file btn-group">' +
' <button id="myButton" type="button" class="btn btn-default btn-sm btn-small" title="My Trigger" tabindex="-1">engage</button>' +
'</div>'
;
$(customButton).appendTo($('.note-toolbar'));
$('#myButton').click(function(event) {
var editor = $('#myEditor');
if (editor.summernote('isEmpty') === false) {
var r = editor.summernote('createRange');
tags.push(r.toString());
r.pasteHTML('<span style="background-color:yellow;" data-tag-index="' + tags.length +'">' + r.toString() + '</span>');
var c = editor.summernote('code');
$('#results').val(c);
}
});
}
}
});
});
I think it works how you like to, but I'm shure you can optimize it a bit. :)
Ok here is my JSFiddle
Greez Eldo.Ob
Upvotes: 3