Tinymce 3 - insert new content in new block after custom button click - javascript

I want to ask if it's possible to add new content "outside" of content that has beed added recently.
So, i have custom button which adds some simple HTML.
And what i want to archive is to add the same html but outside of existing one, so in place marked green on my screenshot. I'm looking for a way how to escape from this div, and add new html after existing one.
below screenshot, and code - how javascript button in generated - very simple.
Thanks for advice.
var oferta = '<div class="col-sm-3"><h1>test</h1></div>'
setup: function (ed) {
ed.addButton('example', {
title: 'example.desc',
image: './/',
text: 'Oferta',
icon: true,
onclick: function () {
tinyMCE.execCommand('mceInsertContent', false, oferta);
}
});
},
EDIT: Below how this looks now when i hit button 3 times in row.(every next content is added to existing one.)

Is very easy to do it try to change you code with this example.
setup: function (editor) {
ed.addButton('example', {
title: 'example.desc',
image: './/',
text: 'Oferta',
icon: true,
onclick: function () {
var h1 = editor.dom.create('h1');
h1.innerText = 'test';
var oferta = editor.dom.create('div' ,{'class': 'col-sm-3'});
oferta.appendChild(h1);
var divs = editor.dom.select('div');
if(divs && divs.length > 0){
editor.dom.insertAfter(oferta,divs[divs.length-1])
}else{
tinyMCE.execCommand('mceInsertContent', false,oferta.outerHTML);
}
editor.selection.select(oferta);
editor.selection.collapse(true);
}
});
},

Related

Quill - pasting custom embed sometimes return boolean instead of actual value

I am using the Quill.js editor, and I have created a custom Embed like below:
var Embed = Quill.import('blots/embed');
class QuillHashtag extends Embed {
static create(value) {
console.log(value);
let node = super.create(value);
node.innerHTML = value;
return node;
}
}
QuillHashtag.blotName = 'hashtag';
QuillHashtag.className = 'quill-hashtag';
QuillHashtag.tagName = 'span';
Quill.register({
'formats/hashtag': QuillHashtag
});
var quill = new Quill('#templateEditor', {
debug: 'debug',
modules: {
toolbar: {
container: '#toolbar'
}
},
placeholder: 'Compose an epic...',
readOnly: false,
theme: 'snow'
});
I then simply have a button, that can insert this custom embed QuillHashtag:
function insertVariable() {
quill.focus();
var selection = this.quill.getSelection();
quill.insertEmbed(selection.index, 'hashtag', '#games');
quill.setSelection(selection.index + selection.length + 1); //Place cursor to the right.
}
This works fine and the embedded hashtag is inserted to the editor. I
Something weird is happening though when I copy the hashtag and pasting it into the editor again and a space is present after the hashtag. When I do this, it will show true instead of the actual hashtag.
The thing is, it only shows the true value when there is a space after the hashtag.
I have created a JSFiddle here.
See below small gif showing this behavior:
I solved this issue by adding the below to the QuillHashtag class:
static value(domNode) {
return domNode;
}

Custom plugin with DOM manipulation CKEditor 4.x

I am developing one custom plugin for the CKEditor 4.7 which do a simple think take in case user select some stuff it will put it in a div with specific class, else it will put a div with same class just with text like 'Add content here'
I try to use some functions according to CKEditor docs but have something really wrong.
here is the code for the plugin folder name=> customdiv, file=> plugin.js
CKEDITOR.plugins.add('customdiv', {
icons: 'smile',
init: function (editor) {
editor.addCommand( 'customdiv',{
exec : function( editor ){
var selection = editor.getSelection();
if(selection.length>0){
selection='<div class="desktop">'+selection+'</div>';
}else{
selection='<div class="desktop">Add your text here </div>';
}
return {
selection
};
}
});
editor.ui.addButton( 'Customdiv',
{
label : 'Custom div',
command : 'customdiv',
toolbar: 'customdiv',
icon : this.path + 'smile.png'
});
if (editor.contextMenu) {
editor.addMenuGroup('divGroup');
editor.addMenuItem('customdiv', {
label: 'Customdiv',
icon: this.path + 'icons/smile.png',
command: 'customdiv',
group: 'divGroup'
});
editor.contextMenu.addListener(function (element) {
if (element.getAscendant('customdiv', true)) {
}
});
}
}
});
According to some docs it have to return the result good.
Also this is how I call them in my config.js file
CKEDITOR.editorConfig = function (config) {
config.extraPlugins = 'templates,customdiv';
config.allowedContent = true;
config.toolbar = 'Custom';
config.toolbar_Custom = [
{ name: 'divGroup', items: [ 'Customdiv' ] },
{name: 'document', items: ['Source', '-', 'Save', 'Preview', '-', 'Newplugin']},
/* MOre plugins options here */
];
};
Note: the official forum was close and moved here :(
UPDATE
I have change the function like this
exec : function( editor ){
var selection = editor.getSelection();
if(selection.length>0){
selection='<div class="desktop">'+selection+'</div>';
CKEDITOR.instances.editor1.insertHtml( selection );
}else{
selection='<div class="desktop">Add your text here </div>';
CKEDITOR.instances.editor1.insertHtml( selection );
}
}
This makes it work for the else part, but still can't get the selected one.
UPDATE 2
After change of the if I can get data if is selected, but when I do insert selected between <div> I face a problem.
var selection = editor.getSelection();
give like result an object, and I funded out a more complex function and I get collected data like this
var selection = editor.getSelection().getNative();
alert(selection);
from this in alert I see the proper selection and not just object,but when I insert it like
CKEDITOR.instances.editor1.insertHtml('<div class="desktop">' + selection + '</div>');
it just put all selected in one line and not adding the div, new div for else case working with this syntax.
UPDATE 3
The problem now is this function
CKEDITOR.instances.editor1.insertHtml('<div>' + selection + '<div>');
it delete all existing HTML tags even if I add just selection without <div> I am not sure if this is because of the way I insert data or way I collect data, just in alert when I collect data I see correct space like in the editor.
user select some stuff it will put it in a div with specific class
If you want to check if selection is not empty, please instead of selection.length>0 try using !selection().getRanges()[0].collapsed.
If you need something more advanced you could also try using
!!CKEDITOR.instances.editor1.getSelection().getSelectedText() to see if any text was selected and !!CKEDITOR.instances.editor1.getSelection().getSelectedElement() to see if any element like e.g. image, tabl,e widget or anchor was selected.
EDIT:
If you need selected HTML please use CKEDITOR.instances.editor1.getSelectedHtml().getHtml();
Please also have a look at CKEditor documentation:
https://docs.ckeditor.com/#!/api/CKEDITOR.editor-method-getSelectedHtml
https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_dom_documentFragment.html#method-getHtml
https://docs.ckeditor.com/#!/api/CKEDITOR.dom.selection-method-getSelectedText
https://docs.ckeditor.com/#!/api/CKEDITOR.dom.selection-method-getSelectedElement

intro.js show and hide data-hint

I want to have a button that can turn on and off the 'hints' function in intro.js.
I have a working version to show and then hide but the show only works once. How can I get it to work repeatedly? This functionality works for the standard data-intro but not for data-hint.
<div class="jumbotron">
<h1 id='step1'>Hints</h1>
<p class="lead">Adding hints using JSON + callbacks</p>
<a id='step2' class="btn btn-large btn-success" href="javascript:void(0);">Add hints</a>
</div>
function addHints(){
intro = introJs();
intro.setOptions({
hints: [
{
element: document.querySelector('#step1'),
hint: "This is a tooltip.",
hintPosition: 'top-middle'
},
{
element: '#step2',
hint: 'More features, more fun.',
position: 'left'
},
{
element: '#step4',
hint: "<b>Another</b> step.",
hintPosition: 'top-middle'
}
]
});
intro.onhintsadded(function() {
console.log('all hints added');
});
intro.onhintclick(function(hintElement, item, stepId) {
console.log('hint clicked', hintElement, item, stepId);
});
intro.onhintclose(function (stepId) {
console.log('hint closed', stepId);
});
intro.addHints();
}
$(function() {
$('#step2').click(function(){
if ( $('#step2').hasClass('clicked') ) {
introJs().hideHints();
$('#step2').removeClass('clicked');
} else {
addHints();
$('#step2').addClass('clicked');
}
});
});
Instead of using hideHints intro.js API method just remove the div block of intro.js from DOM:
var introDiv = document.getElementsByClassName("introjs-hints")[0];
introDiv.parentNode.removeChild(introDiv);
(You can do the same thing with jQuery if you want to).
When the div is removed from DOM, just initialize hints once again as you do with your addHints method when you want to show hints and it'll work.
Instead of deleting the div block with javascript. You can use .removeHints()
This function is part of intro.js, but is not included in the documentation.
Perhaps a bit hacky, but this works for me...
First, put your hints into their own variable:
hints = [{...}, ...]
then, reset your hints in the intro options
intro.onhintclose(function(stepId) {
if (document.querySelectorAll('.introjs-hidehint').length === hints.length) {
intro.setOptions({hints: hints})
}
})
The hidden hints are given a class of introjs-hidehint, and document.querySelectorAll will return all of them in an array. Once that array is the same size as your hints array, reset your hints in your intro options and that will reset all your hints so you can show them all again.
Here's a more complete example that also allows:
(a) toggling hints on/off by clicking a button (located on a nav bar so used across multiple pages).
(b) once all hints have been clicked, the hints div gets removed so that clicking show hints button will again actually...show hints...
(c) allow you to store hints for multiple pages in a single json object array (re: nav bar).
var jquery = require('jquery');
var introJs = require('intro.js');
* ===========================================================================
* define onclick of hints button
* =========================================================================*/
jquery('#hints_button').on('click', function() {
if (document.getElementsByClassName('introjs-hints').length == 0){
addSomeHints();
}
else {
destroyHints();
};
});
/* ===========================================================================
* Add hints using the IntroJS library
* =========================================================================*/
/* define hints */
var theHints = [
{
element: document.querySelector('#step1'),
hint: "This is a tooltip.",
hintPosition: 'top-middle'
},
{
element: '#step2',
hint: 'More features, more fun.',
hintPosition: 'left'
},
{
element: '#step4',
hint: "<b>Another</b> step.",
hintPosition: 'top-middle'
}
];
/* generate hints with introjs */
function addSomeHints() {
intro = introJs();
intro.setOptions({
hints: theHints
});
intro.onhintclose(function (stepId) {
var remaining_hints = all_hints - document.getElementsByClassName("introjs-hidehint").length;
if (remaining_hints == 0) {
destroyHints();
};
});
/* add hints */
intro.addHints();
/* store number of hints created */
var all_hints = document.getElementsByClassName('introjs-hint').length;
};
/* remove hints div */
function destroyHints() {
var hintsDiv = document.getElementsByClassName("introjs-hints")[0]
hintsDiv.parentNode.removeChild(hintsDiv);
};
... hopefully this saves someone the 20 minutes it took me to piece together the answers and adapt it for what seems like a super common use case.

Can not change text when using Localization Sencha ExtJs

I has question about Localization,
I create key in Labels.js file, code :
Ext.define('Portal.Labels', {
singleton: true,
title: ''
});
And in event click of button, I using:
var main = Ext.getCmp('main'); // Get main (container) and destroy it.
main.destroy();
// Sure main is destroyed.
// Get url of local.
var url = Ext.util.Format.format('ext/packages/ext-locale/overrides/vn/ext-locale-vn.js');
// Sure url is loaded.
// Load script local file.
Ext.Loader.loadScript({
url: url,
scope: this
}
);
// Create main and show it.
main = Ext.create('main');
main.show();
In ext-locale-vn.js, I add :
Ext.define("Portal.locale.vn.Labels", {
override: "Portal.Labels",
title: "DASHBOARD"
});
In main container, I create lable:
xtype: 'label',
text:Portal.Labels.title
But when I click button, text of label still not change to "DASHBOARD", I don't know where I was wrong, please help me.

Programmatic dijit creation causes dojo event chain to break

I'm having some problem handling the JS onClick event and Dojo.
Waht i'm trying to achieve is to somehow edit data from the first cell inline.
Consider this HTML:
<table class="datatable" id="officestable" name="officestable">
<tr>
<td>xxxxx</td>
<td>
<button id="officeeditbtn3" data-dojo-type="dijit.form.Button" type="button" data-dojo-props="iconClass:'advanEditIcon',onClick: function() { editOfficeFieldInline(this, 3); }">Edit</button>
<button id="officeconfigbtn3" data-dojo-type="dijit.form.Button" type="button" data-dojo-props="iconClass:'advanConfigIcon',onClick: function() { configOffice(this, 3); }">Config</button>
<button id="officeremovebtn3" data-dojo-type="dijit.form.Button" type="button" data-dojo-props="iconClass:'advanRemoveIcon',onClick: function() { removeOffice(this, 3); }">Remove</button>
</td>
</tr>
To handle all this i have the following (relevant) methods in javascript.
function editOfficeFieldInline(buttonElem, officeid) {
var table = document.getElementById("officestable"); //get table
var operationsCell = buttonElem.domNode.parentNode; // get second cell where button are
var trline = operationsCell.parentNode; // get tr element
var dataCell = trline.firstChild; // get cell where data is to be edited
var currentContent = dataCell.innerHTML; // ... self explainable...
var tdcellHTML;
tdcellHTML = "<input id=\"editofficebox\" type=\"text\">"; // adding an input placeholder
dataCell.innerHTML = tdcellHTML; // replace cell content with edit box
// attach dijit to pre-created edit box
var editofficebox = new dijit.form.TextBox({
value: currentContent,
style: {
width: "190px",
}
},
"editofficebox");
addSaveCancelButtons(table,
operationsCell,
function(){
// 'save' actions
// save new data using ajax (working!)
saveOfficeName(officeid, dataCell, currentContent, operationsCell);
},
function(){
// 'cancel' actions
destroyOfficeFieldInline(table, false);
setCellVal(dataCell, currentContent);
}
);
}
function addSaveCancelButtons(table, operationsCell, saveAction, cancelAction) {
operationsCell.innerHTML += "<button id=\"savebutton\">Save</button>";
operationsCell.innerHTML += "<button id=\"cancelbutton\">Cancel</button>";
var savebutton = new dijit.form.Button({
iconClass: "advanSaveIcon",
onClick: saveAction
},
"savebutton");
var cancelbutton = new dijit.form.Button({
iconClass: "advanCancelIcon",
onClick: cancelAction,
},
"cancelbutton");
}
// this is a generic function. parameters are not really needed in this case
function destroyOfficeFieldInline(tableElement, bNew) {
dijit.byId("editofficebox").destroy();
destroySaveCancelButtons();
if (bNew) {
destroyNewRow(tableElement);
}
}
function destroySaveCancelButtons() {
dijit.byId("savebutton").destroy();
dijit.byId("cancelbutton").destroy();
}
function setCellVal(cell, val) {
cell.innerHTML = val;
}
Now, the code works for the first time.
But somehow, if I click "cancel" after clicking "edit", then pressing "edit" again will do nothing. The dynamic fields will not be created again.
I'm guessing that something is not being cleaned up correctly, but i ran out of ideas...
What's wrong with this code?
PS.I'm open to alternative ways to achieve this...
[EDIT]
I found that these seem to be the offending lines of code:
operationsCell.innerHTML += "<button id=\"savebutton\">Save</button>";
operationsCell.innerHTML += "<button id=\"cancelbutton\">Cancel</button>";
As soon as the first one is executed, all buttons within the cell lose their event listeners, namely, onclick.
Anyone knows the reason for this?
May be this one will help you..
first of all you have to store the id of button the the temp variable and you have to use that variable to destroy controls
for example
var temp = dijit.byId('savebutton');
temp.destroy();
i hope this will help you.
Ok. Just figured out what was going on (with the help from Dojo community) so i came back here to share the solution.
The innerHTMl was (supposedly) appended with the new button tags, but in fact it was being replaced, because of the way the += operator works.
When replaced, the original contents were destroyed, and then recreated, but this time without its event listeners / events.
So, the solution is to use the dijit placeAt method:
function addSaveCancelButtons(table, operationsCell, saveAction, cancelAction) {
var savebutton = new dijit.form.Button({
id: "savebutton",
iconClass: "advanSaveIcon",
label: "Guardar",
onClick: saveAction
}).placeAt(operationsCell);
var cancelbutton = new dijit.form.Button({
id: "cancelbutton",
iconClass: "advanCancelIcon",
label: "Cancelar",
onClick: cancelAction,
}).placeAt(operationsCell);
}

Categories