CKEDITOR - how to add permanent onclick event? - events

I am looking for a way to make the CKEDITOR wysiwyg content interactive. This means for example adding some onclick events to the specific elements. I can do something like this:
CKEDITOR.instances['editor1'].document.getById('someid').setAttribute('onclick','alert("blabla")');
After processing this action it works nice. But consequently if I change the mode to source-mode and then return to wysiwyg-mode, the javascript won't run. The onclick action is still visible in the source-mode, but is not rendered inside the textarea element.
However, it is interesting, that this works fine everytime:
CKEDITOR.instances['editor1'].document.getById('id1').setAttribute('style','cursor: pointer;');
And it is also not rendered inside the textarea element! How is it possible? What is the best way to work with onclick and onmouse events of CKEDITOR content elements?
I tried manually write this by the source-mode:
<html>
<head>
<title></title>
</head>
<body>
<p>
This is some <strong id="id1" onclick="alert('blabla');" style="cursor: pointer;">sample text</strong>. You are using CKEditor.</p>
</body>
</html>
And the Javascript (onclick action) does not work. Any ideas?
Thanks a lot!
My final solution:
editor.on('contentDom', function() {
var elements = editor.document.getElementsByTag('span');
for (var i = 0, c = elements.count(); i < c; i++) {
var e = new CKEDITOR.dom.element(elements.$.item(i));
if (hasSemanticAttribute(e)) {
// leve tlacitko mysi - obsluha
e.on('click', function() {
if (this.getAttribute('class') === marked) {
if (editor.document.$.getElementsByClassName(marked_unique).length > 0) {
this.removeAttribute('class');
} else {
this.setAttribute('class', marked_unique);
}
} else if (this.getAttribute('class') === marked_unique) {
this.removeAttribute('class');
} else {
this.setAttribute('class', marked);
}
});
}
}
});

Filtering (only CKEditor >=4.1)
This attribute is removed because CKEditor does not allow it. This filtering system is called Advanced Content Filter and you can read about it here:
http://ckeditor.com/blog/Upgrading-to-CKEditor-4.1
http://ckeditor.com/blog/CKEditor-4.1-Released
Advanced Content Filter guide
In short - you need to configure editor to allow onclick attributes on some elements. For example:
CKEDITOR.replace( 'editor1', {
extraAllowedContent: 'strong[onclick]'
} );
Read more here: config.extraAllowedContent.
on* attributes inside CKEditor
CKEditor encodes on* attributes when loading content so they are not breaking editing features. For example, onmouseout becomes data-cke-pa-onmouseout inside editor and then, when getting data from editor, this attributes is decoded.
There's no configuration option for this, because it wouldn't make sense.
Note: As you're setting attribute for element inside editor's editable element, you should set it to the protected format:
element.setAttribute( 'data-cke-pa-onclick', 'alert("blabla")' );
Clickable elements in CKEditor
If you want to observe click events in editor, then this is the correct solution:
editor.on( 'contentDom', function() {
var element = editor.document.getById( 'foo' );
editor.editable().attachListener( element, 'click', function( evt ) {
// ...
// Get the event target (needed for events delegation).
evt.data.getTarget();
} );
} );
Check the documentation for editor#contentDom event which is very important in such cases.

Related

why isn't the checkbox change event triggered when i do it programatically in d3js

So I have a function that changes the checkbox
somefunction() {
d3.select("input").property("checked", true);
}
and in another function I have that detects a change in the checkbox like this:
d3.selectAll("input").on("change", change);
The problem I have is when it changes the checkbox without me clicking on it, it will not detect it as a "proper" change. What can I do to make it detect something else changing it as a "proper" change?
d3 is using the standard addEventListener in it's on method. The problem you have is that changing the checked property doesn't raise any events for the addEventListener to hear. The proper way would be to just call the handler yourself after setting the proptery:
var myInput = d3.select("input");
myInput.property("checked", true);
myInput.on("change")(); // call it yourself
Full working code:
<!DOCTYPE html>
<html>
<head>
<script data-require="d3#3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
</head>
<body>
<input type="checkbox" />
<script>
var checked = false;
setInterval(function(){
checked = !checked;
var myInput = d3.select("input");
myInput.property("checked", checked);
myInput.on("change")();
}, 2000);
d3.select("input").on("change", function(d){
console.log('checkbox changed');
});
</script>
</body>
</html>
The solution suggested by Mark works flawlessly however just alternatively I would also like to mention that rather than calling the event handler yourself you can trigger the event yourself and leave rest of the code as it is. The onchange event is triggered on following sequence focus-valueChange-unfocus. Now this does not happen when you change it without clicking on it, the value changes but no focus. Anyway so instead of relying on that you can just trigger onchange event yourself. I created a fiddle here which explains it. Hope it helps: https://jsfiddle.net/xcjje9r3/6/
window.clickMe = function() {
tmp = d3.select('#cbox');
if (tmp.property('checked') == false) tmp.property('checked', true);
else tmp.property('checked', false);
tmp[0][0].dispatchEvent(evt); //MANUALLY TRIGGER EVENT
}
//tmp[0][0] is becoz d3.select returns an array and [0][0] position stores the actual DOM element in this array.
window.listenerInitialize = function() {
evt = document.createEvent("HTMLEvents"); //CREATE NEW EVENT WITH TYPE
evt.initEvent("change", false, true); //THE EXACT EVENT TO FIRE
d3.select('#cbox').on('change', alerting); //ADDING LISTENER FOR EVENT
}
window.alerting = function() {
alert('testEvent');
}

Rich Text Editor (WYSIWYG) in CRM 2013

Sometimes it is useful to have the HTML editor in CRM interface. It is possible to implement the editor directly to CRM 2013. As editor we will use ckeditor which allows to use it without installation on the server.
Identify the field where you would like to use the rich text editor.
Create html-webresource which will define ckeditor. Go to Settings-Customizations-Customize the System-Web Resources.
In html editor of web resource, select the Source tab and insert the following code:
<html>
<head>
<title></title>
<script src="//cdn.ckeditor.com/4.4.7/standard/ckeditor.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function getTextFieldName()
{
var vals = new Array();
if (location.search != "")
{
vals = location.search.substr(1).split("&");
for (var i in vals)
{
vals[i] = vals[i].replace(/\+/g, " ").split("=");
}
//look for the parameter named 'data'
for (var i in vals)
{
if (vals[i][0].toLowerCase() == "data")
{
var datavalue = vals[i][2];
var vals2 = new Array();
var textFieldName = "";
vals2 = decodeURIComponent(datavalue).split("&");
for (var i in vals2)
{
var queryParam = vals2[i].replace(/\+/g, " ").split("=");
if (queryParam[0] != null && queryParam[0].toLowerCase() == "datafieldname")
{
textFieldName = queryParam[1];
}
}
if (textFieldName == "")
{
alert('No "dataFieldName" parameter has been passed to Rich Text Box Editor.');
return null;
}
else
{
return textFieldName;
}
}
else
{
alert('No data parameter has been passed to Rich Text Box Editor.');
}
}
}
else
{
alert('No data parameter has been passed to Rich Text Box Editor.');
}
return null;
}
CKEDITOR.timestamp = null;
​// Maximize the editor window, i.e. it will be stretched to target field
CKEDITOR.on('instanceReady',
function( evt )
{
var editor = evt.editor;
editor.execCommand('maximize');
});
var Xrm;
$(document).ready(function ()
{
​ // Get the target field name from query string
var fieldName = getTextFieldName();
var Xrm = parent.Xrm;
var data = Xrm.Page.getAttribute(fieldName).getValue();
document.getElementById('editor1').value = data;
/*
// Uncomment only if you would like to update original field on lost focus instead of property change in editor
//Update textbox on lost focus
CKEDITOR.instances.editor1.on('blur', function ()
{
var value = CKEDITOR.instances.editor1.getData();
Xrm.Page.getAttribute(fieldName).setValue(value);
});
*/
// Update textbox on change in editor
CKEDITOR.instances.editor1.on('change', function ()
{
var value = CKEDITOR.instances.editor1.getData();
Xrm.Page.getAttribute(fieldName).setValue(value);
});
// Following settings define that the editor allows whole HTML content without removing tags like head, style etc.
CKEDITOR.config.allowedContent = true;
CKEDITOR.config.fullPage = true;
});
</script>
<meta>
</head>
<body style="word-wrap: break-word;">
<textarea class="ckeditor" cols="80" id="editor1" name="editor1" rows="10"></textarea>
</body>
</html>
Note:
As you can see, there are a few important sections
a) The following code loads the ckeditor and jquery from web so that they don't have to be installed on server.
<script src="//cdn.ckeditor.com/4.4.7/standard/ckeditor.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
b) Function getTextFieldName() which gets the name of target field where should be rich text editor placed. This information is obtained from query string. This will allow to use this web resource on multiple forms.
c) Initialization of ckeditor itself - setting the target field and properties of ckeditor. Also binding the editor with predefined textarea on the page.
Open the form designer on the form where you would like to use ​WYSIWYG editor. Create a text field with sufficient length (e.g. 100 000 chars) which will hold the html source code.
Insert the iframe on the form. As a webresource use the resource created in previous steps. Also define Custom Parameter(data) where you should define the name of the text field defined in step 4. In our situation we created new_bodyhtml text field so the parameter holds this value. This value is returned by the getTextFieldName() of the web resource.
Do not forget to save and publish all changes in CRM customization otherwise added webresources and updated form are not available.
That's all, here is example how it looks like:
Yes, you can use CKEditor, but when I implemented the CKEditor on a form, it turns out it is quite limited in the functionality in provides. Also, the HTML it generates leaves much to be desired. So, I tried a similar idea to Pavel's but using a backing field to store the actual HTML using TinyMCE. You can find the code here:
Javascript
HTML
Documentation
I have package my solution as a managed and unmanaged CRM solution that can be imported and utilised on any form. Moreover, it works on both CRM 2013 and CRM 2015

syncronized scroll does not work in div based ckeditor

Basically i have 2 instances of ckeditor on a single page. One on the left and another in the right side of the page.
The left editor uses a div rather than traditional iframe. I've done this by removing the iframe plugin and including the div editing area plugin.
The right editor loads in an iframe and but is also div based(i can use the iframe editor as well on the right if required, not an issue).
Now if the cursor/focus is on the right editor's content area then the left editor should scroll along with it. I've tried to use the code as provied by Reinmar in below url but it seems to work only with editors based on iframe on both sides. Also please note that i'm using jquery adapter for initializing the editors.
CKEDITOR how to Identify scroll event
I initialized the editor on left as below:
var editor_left = $( '#editor_left' ).ckeditor();
And below is my code for the right editor:-
var editor_right = $( '#editor_right' ).ckeditor();
editor_right.editor.on( 'contentDom', function() {
var editable = editor_right.editor.editable();
editable.attachListener( editable.getDocument(), 'scroll', function() {
alert('scroll detected');
parent.$('#left_editor_content_area').scrollTop($(this).scrollTop())
});
});
If i use the iframe based editor on the right then i'm able to get the "scroll detected" alert. But the scrollTop() function still does not work as expected
Any help will be appreciated.
The code that you mentioned is right. You got to update scrollTop property of the div-based editable with the scroll position of the window inside the iframe-based editor (JSFiddle).
var editor_div = CKEDITOR.replace( 'editor_div', {
extraPlugins: 'divarea'
} );
CKEDITOR.replace( 'editor_iframe', {
on: {
contentDom: function() {
var editable = this.editable(),
win = this.document.getWindow(),
doc = editable.getDocument();
editable.attachListener( doc, 'scroll', function( evt ) {
// Get scroll position of iframe-based editor.
var scroll = win.getScrollPosition();
// Update scroll position in the div-based editor.
editor_div.editable().$.scrollTop = scroll.y;
} );
}
}
} );

jQuery .on() event doesn't work for dynamically added element

I'm making a project where a whole div with buttons is being inserted dynamically when user click a button, and inside that div there's a button, which when the user click on it, it does something else, like alerting something for example.
The problem is when i press on that button in the dynamically added div, nothing happens. The event doesn't fire at all.
I tried to add that div inside the HTML and try again, the event worked. So i guess it's because the div is dynamically added.
The added div has a class mainTaskWrapper, and the button has a class checkButton.
The event is attached using .on() at the end of script.js file below.
Here's my code :
helper_main_task.js : (that's the object that adds the div, you don't have to read it, as i think it's all about that div being dynamically added, but i'll put it in case you needed to)
var MainUtil = {
tasksArr : [],
catArr : ["all"],
add : function(){
var MTLabel = $("#mainTaskInput").val(), //task label
MTCategory = $("#mainCatInput").val(), //task category
MTPriority = $("#prioritySlider").slider("value"), //task priority
MTContents = $('<div class="wholeTask">\
<div class="mainTaskWrapper clearfix">\
<div class="mainMarker"></div>\
<label class="mainTaskLabel"></label>\
<div class="holder"></div>\
<div class="subTrigger"></div>\
<div class="checkButton"></div>\
<div class="optTrigger"></div>\
<div class="addSubButton"></div>\
<div class="mainOptions">\
<ul>\
<li id="mainInfo">Details</li>\
<li id="mainEdit">Edit</li>\
<li id="mainDelete">Delete</li>\
</ul>\
</div>\
</div>\
</div>');
this.tasksArr.push(MTLabel);
//setting label
MTContents.find(".mainTaskLabel").text(MTLabel);
//setting category
if(MTCategory == ""){
MTCategory = "uncategorized";
}
MTContents.attr('data-cat', MTCategory);
if(this.catArr.indexOf(MTCategory) == -1){
this.catArr.push(MTCategory);
$("#categories ul").append("<li>" + MTCategory +"</li>");
}
$("#mainCatInput").autocomplete("option", "source",this.catArr);
//setting priority marker color
if(MTPriority == 2){
MTContents.find(".mainMarker").css("background-color", "red");
} else if(MTPriority == 1){
MTContents.find(".mainMarker").css("background-color", "black");
} else if(MTPriority == 0){
MTContents.find(".mainMarker").css("background-color", "blue");
}
MTContents.hide();
$("#tasksWrapper").prepend(MTContents);
MTContents.slideDown(100);
$("#tasksWrapper").sortable({
axis: "y",
scroll: "true",
scrollSpeed : 10,
scrollSensitivity: 10,
handle: $(".holder")
});
}
};
script.js : (the file where the .on() function resides at the bottom)
$(function(){
$("#addMain, #mainCatInput").on('click keypress', function(evt){
if(evt.type == "click" || evt.type =="keypress"){
if((evt.type =="click" && evt.target.id == "addMain") ||
(evt.which == 13 && evt.target.id=="mainCatInput")){
MainUtil.add();
}
}
});
//Here's the event i'm talking about :
$("div.mainTaskWrapper").on('click', '.checkButton' , function(){
alert("test text");
});
});
It does not look like div.mainTaskWrapper exist.
From the documentation (yes, it is actually bold):
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page.
[...]
By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.
You might want to bind it to #tasksWrapper instead:
$("#tasksWrapper").on('click', '.checkButton' , function(){
alert("test text");
});
You need to specify a selector with on (as a parameter) to make it behave like the old delegate method. If you don't do that, the event will only be linked to the elements that currenly match div.mainTaskWrapper (which do not exists yet). You need to either re-assign the event after you added the new elements, or add the event to an element that already exists, like #tasksWrapper or the document itself.
See 'Direct and delegate events' on this page.
I know this is an old post but might be useful for anyone else who comes across...
You could try:
jQuery('body')on.('DOMNodeInserted', '#yourdynamicallyaddeddiv', function () {
//Your button click event
});
Here's a quick example - https://jsfiddle.net/8b0e2auu/

Watermark text in CKEditor

Do you know how to add watermark in CKEditor (visual word processor)?
I want the behavior like this: When the CKEditor is loaded, it has text by default. When I click on it, text must disappear.
Below are the steps to add water mark in CKEditor
Generally when you set default text in Ck Editor through java script on page load. JavaScript event get fired before the control actually load so if possible set the text for code behind.
Attaching Events in Javascript for OnFocus and OnBlur
$(document).ready(function() {
var myeditor = CKEDITOR.instances['EditorId'];
myeditor.on("focus", function(e) {
RemoveDefaultText();
});
myeditor.on("blur", function(e) {
setDefaultText();
});
});
Define your default text in this function
function setDefaultText() {
if (CKEDITOR.instances['EditorId'].getData() == '') {
CKEDITOR.instances['EditorId'].setData('Your Message Here');
}
}
function RemoveDefaultText() {
if (CKEDITOR.instances['EditorId'].getData().indexOf('Your Mesage Here') >= 0) {
CKEDITOR.instances['EditorId'].setData('');
CKEDITOR.instances['EditorId'].focus();
}
}
You can also define styles to the water mark by adding classes to the default text and place the class into you ck editor content css otherwise it will not work
A ready to use plugin can be tested here. It allows to customize the default text and it takes into acount, dialogs as well as reading the data from an external script.
You might want to try this jQuery plugin:
https://github.com/antoineleclair/ckwatermark

Resources