How to Destroy and Reinitialize CKEDITOR Again? - javascript

I use the below code to destroy the editor instance.
editor.destroy();
After this, I try to initialize CKEditor and set content using the below code.
CKEDITOR.replace('editor1');
CKEDITOR.instances['editor1'].setData("MY HTML DATA");
But when I am doing like this only the empty HTML page is Shown.
How can I do this in a Correct Way?

If i understand you correctly, following fiddle will help you in initializing and destroying ckeditor.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CKEditor</title>
<script src="https://cdn.ckeditor.com/4.8.0/standard/ckeditor.js"></script>
</head>
<body>
<div name="editor1">TEST CONTENT</div>
<button id="toogleEditor">
TOOGLE EDITOR
</button>
</body>
</html>
Here is the JS
var editorInstance;
document.getElementById('toogleEditor').addEventListener('click',function() {
if (CKEDITOR) {
if (editorInstance) {
editorInstance.destroy();
editorInstance = undefined;
} else {
editorInstance = CKEDITOR.replace('editor1');
editorInstance.setData("MY HTML DATA");
}
}
})
Fiddle

Operations you have described require time to complete thus please use events to control when editor gets created and destroyed:
https://docs.ckeditor.com/ckeditor4/latest/api/CKEDITOR_editor.html#event-instanceReady
https://docs.ckeditor.com/ckeditor4/latest/api/CKEDITOR.html#event-instanceDestroyed
var editor = CKEDITOR.replace( 'editor1', {
language: 'en'
});
// Recreate editor after it has been destroyed
CKEDITOR.on( 'instanceDestroyed', function() {
CKEDITOR.replace('editor1');
} );
// Set editor data after it has been created
CKEDITOR.on( 'instanceReady', function( evt ) {
evt.editor.setData("MY HTML DATA");
} );

Related

Unbeleivable, same Javascript code do not behave the same way in JSFiddle

I wrote the same code in two JSFiddle, and they do not behave the same way :
HTML:
<p id='complete'></p>
JS:
document.onreadystatechange=fnStartInit;
function fnStartInit()
{
var state = document.readyState
if (document.readyState === 'complete')
{
document.getElementById('complete').innerHTML = 'Document completely loaded'
}
}
Working JSFiddle: https://jsfiddle.net/Imabot/toujsz7n/9/
Non working JSFiddle: https://jsfiddle.net/Imabot/3sLcpa0y/7/
Why do they not behave the same way?
Your first link has the load setting "No wrap - bottom of <head>".
This is equivalent to having HTML like
<head>
<script>
// YOUR SCRIPT HERE
</script>
<head>
<body>
// YOUR HTML HERE
</body>
Your second link has the load setting "On Load":
This is equivalent to having HTML like
<head>
<script>
window.onload = function() {
// YOUR SCRIPT HERE
}
</script>
<head>
<body>
// YOUR HTML HERE
</body>
You can see this if you Inspect the iframe in the lower right. So by the time the second script runs, readystatechange never fires again, so fnStartInit never runs.
Here's a Stack Snippet demonstrating the same problem:
window.onload = () => {
console.log('onload');
document.onreadystatechange = () => {
console.log('ready state just changed');
};
};

Trying to add a javascript function to a button

I'm relatively new to HTML so please bear with me. I'm trying to add a simple javascript function that was already provided to me that grabs images from Flickr to a button. When I click the button, nothing happens. I'm not sure where the error is occuring but I think it has something to do with the function not executing correctly.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>getJSON</title>
<meta charset="utf-8" />
<script src="jquery-3.1.1.min.js"></script>
</head>
<body>
<button onclick="myFunction()">Click me</button>
<script>
function myFunction()
{ //Functions don't need names. This function will simply run when the page loads
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
$.getJSON( flickerAPI,
{ // The "$" simply refers to jQuery. This calls the getJSON function that is found inside jquery-3.1.1.min.js
tags: "Baruch College", //Some filter information in the format set by Flickr, who owns the JSON
tagmode: "any",
format: "json"
})
.done(function( data )
{ //Here, a an unnamed function is created made into the event handler for the "done" event... in other words, this is the code that will manifest itself when the getJSON is done.
$.each( data.items, function( i, item )
{
$( "<img>" ).attr( "src", item.media.m ).appendTo( "#images" );
if ( i === 5 )
{
return false;
}
});
});
}
</script>
</body>
</html>
I uploaded the jquery script mentioned in the HTML: http://pastebin.com/2CfRNkvq
You need to specify where the images will be placed after they are retrieved. In the JavaScript code, you can see that for each image, it creates an <img> tag and appends it to the element with id="images".
Just add id="images" to the button element like this:
<button onclick="myFunction()" id="images">Click me</button>
When you click the button, the images will be placed inside the button.

CodeMirror - load file on editor on page load

I'd like to load inside the Codemirror editor a local file on page load, I've tried using FilerReader APIs without success. I also tried to use the jquery .load() function but I can only load a file in a generic textarea not in the editor.
On page load could wait for data request to complete before initializing codemirror
Since jQuery mentioned will use it for example
$(function(){
$.get('path/to/codefile', function(data){
$('textarea#editorId').val(data);
// now init codemirror
})
})
You can load the content to a <textarea> like you've done previously and then initialize CodeMirror instance with CodeMirror.fromTextArea-method.
var myTextArea = document.getElementById("myTextArea");
var myCodeMirror = CodeMirror.fromTextArea(myTextArea{
lineNumbers: true,
mode: "javascript"
});
For more information see Basic Usage on CodeMirror documentation
Here is sample of the code:
<script src="codemirror/lib/codemirror.js"></script>
<link rel="stylesheet" href="codemirror/lib/codemirror.css"/>
<script src="codemirror/mode/clike/clike1.js"></script>
<script src="codemirror/mode/javascript/javascript.js"></script>
<div id="editor"> </div>
<div>
<input type="file" onchange="localLoad(this.files);" />
</div>
<script>
var myCodeMirror = CodeMirror(
document.getElementById('editor'), {
lineNumbers: true
});
function localLoad(files) {
if (files.length == 1) {
document.title = escape(files[0].name);
var reader = new FileReader();
reader.onload = function(e) {
myCodeMirror.setValue(e.target.result);
};
reader.readAsText(files[0]);
}
}
</script>
The above one is done for div. If you wanted for textarea, change it like:
<textarea id="editor" name="field1"></textarea>
<script>
var myCodeMirror = CodeMirror.fromTextArea
document.getElementById('editor'),{
lineNumbers: true
});
myCodeMirror.setSize(null, 600);
</script>

How to include a jquery plugin in your code

This may be a really dumb question but I'm having trouble including a jquery plugin in my code.
The plugin I'm referring to is: http://davidlynch.org/projects/maphilight/docs/
I want to mimic something very similar to the following:
http://jsfiddle.net/keith/PVpgK/
But when I copy the code over, I keep getting error messages saying "maphilight is not a function"
How do I use a jquery plugin in my code? Thank you
$(function() {
//using the jquery map highlight plugin:
//http://davidlynch.org/js/maphilight/docs/
//initialize highlight
$('.map').maphilight({strokeColor:'808080',strokeWidth:0,fillColor:'00cd27'});
//hover effect
$('#maplink1').mouseover(function(e) {
$('#map1').mouseover();
}).mouseout(function(e) {
$('#map1').mouseout();
}).click(function(e) { e.preventDefault(); });
// initialize tabbing
$(".tabs area:eq(0)").each(function(){
$(this).addClass("current");
});
$(".tab-content").each(function(){
$(this).children(":not(:first)").hide();
});
//map clicks
$(".tabs area").click(function(){
//This block is what creates highlighting by trigger the "alwaysOn",
var data = $(this).data('maphilight') || {};
data.alwaysOn = !data.alwaysOn;
$(this).data('maphilight', data).trigger('alwaysOn.maphilight');
//there is also "neverOn" in the docs, but not sure how to get it to work
if ($(this).hasClass("current") == false)
{
var thisTarget = $(this).attr("href");
$(this).parents(".tabs").find('area.current').removeClass('current');
$(this).addClass('current');
$(this).parents(".tabs").nextAll(".tab-content").children(":visible").fadeOut(1, function() {
$(thisTarget).fadeIn("fast");
});
}
return false;
});
});
You need to include the link to jquery in your html header.
1) Download jquery from jQuery.com
2) Link to downloaded file in your header
Like so:
<head>
...
<script src="/path/to/jquery-1.11.3.min.js"></script>
...
</head>
As the previous answer. But put them in the bottom of the body tag.
<html>
<head>
</head>
<body>
<script src="../path/to/jquery-1.11.3.min.js"></script>
<script src="http://davidlynch.org/js/maphilight/jquery.maphilight.min.js"></script>
</body>
</html>
you need to add the following to the header of your html code
<script type="text/javascript" src="http://davidlynch.org/js/maphilight/jquery.maphilight.min.js">
</script>

jQuery + Module Pattern: When to declare/query elements?

Typically, you don't start querying the DOM until the $(document).ready().
In both of the options below, the Widget is declared (and the elements are queried) outside of the $(document).ready().
Is this OK? Can I initialize the jQuery elements (as long as I'm not manipulating anything), OUTSIDE of the ready handler?
Would it be better to put this whole Widget definition inside the $(document).ready()?
Should I wait until the Widget.init() to query the elements?
Note: I'm brand new to JS design patterns, so please note if I'm missing something
Option1
Widget = {
ele : $('#ele'),
init : function(){ ... }
};
$(document).ready(function(){
Widget.init();
});
Option2
Widget = (function(){
var privateEle = $('#privateEle');
return {
publicEle: $('#publicEle'),
init: function(){ ... }
};
}());
$(document).ready(function(){
Widget.init();
});
What I would do:
var Widget = (function(){
var ele;
function init(_ele){
ele = _ele;
};
return {
init: init
};
})();
$(function(){
Widget.init( $('#foo') );
});
If your script is loaded before jquery, you will not see an error "undefined is not a function". But, if you perform a query before domReady, you could get unexpected result, ele = []
EDIT: btw.. put your <script> tags before </body> NOT within <head></head>
It won't work because at the time when you query the element, the element is not there yet, thus your query will return an empty jQuery selection. You can only query for elements when the DOM is ready.
what would work though is on of the following:
create the element outside $(document).ready(). note that you have to provide the full html or work with $(..).attr(x,y) and the likes.
Widget = {
ele : $("<div id='ele'>"),
....
}
or you can query the element on widget initialization.
Widget = {
ele : "#ele",
init : function(){
this.ele = $(this.ele);
...
}
}
You can include script just before body end tag.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Demo</title>
</head>
<body>
<!-- my HTML -->
<script src="../js/vendor/jquery-1.9.1.js"></script>
<script src="../js/vendor/jquery-migrate-1.1.1.js"></script>
<script src="../js/custom.js"></script>
</body>
</html>
DOM is ready (no need for $(document).ready):
/*custom.js */
var Widget = (function($){
var _$element;
return {
init: function(){
_$element = $('#myElementId');
// TODO - element is available from now on
};
};
}(jQuery));
Widget.init();

Categories

Resources