CodeMirror - load file on editor on page load - javascript

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>

Related

How to Destroy and Reinitialize CKEDITOR Again?

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");
} );

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>

Javascript: Function does not get fired

I have somehow a beginner's question about the following structure:
<body>
<p id="text_object">Some text</p>
<button id="button_change_text">change text on click</button>
// Individual script on page template
// ----------------------------------
<script type="text/javascript">
var object = $('#text_object');
changeTextOnLoad(object);
</script>
// Footer from included footer.php with universal main.js file
// ------------------------------------------------------------
<footer>
<script type="text/javascript" src="main.js">
</footer>
</body>
My main.js contains the following:
// declaration of function for writing new text into text object on load
function changeTextOnLoad(object) {
object.text('New text');
}
// declaration of click function
$('#button_change_text').on('click', function() {
$('#text_object').text('New text');
});
My problem: My console tells me that changeTextOnLoad() is undefined. But clicking on the button and changing the text by this way works perfectly fine. Where is the reason? Why in my main.js file does the click function get fired but not the changeTextOnLoad function?
You are calling your changeTextOnLoad function before the main.js file has loaded. Either put the function call in an onload event callback or put the include above the call
window.onload = function(){
var object = $('#text_object');
changeTextOnLoad(object);
};
//Or using addEventListener
window.addEventListener("load",function(){
var object = $('#text_object');
changeTextOnLoad(object);
});
//Or since you are using jQuery
$(document).ready(function(){
var object = $('#text_object');
changeTextOnLoad(object);
});
//Or
$(function(){
var object = $('#text_object');
changeTextOnLoad(object);
});
OR
<script type="text/javascript" src="main.js"></script>
<script type="text/javascript">
var object = $('#text_object');
changeTextOnLoad(object);
</script>
because main.js is another file, browser takes time to download it. But you run changeTextOnLoad(object); before that.

$.html renders script as content

For a project i'm dynamically loading content that consist of html and javascript. Until now i was using jquery 1.8.3 but while cleaning up i wanted to update to 1.10.1.
I've narrowed my problem down to the way i use the $.html() function on my content div.
In jquery 1.8.3:
var content = $("#content");
contentDiv.html("<script> alert('Testing'); </script>")
shows a alertbox with the content 'Testing', while in newer jquery versions the same code the string is inserted into the DOM and then the alertbox also appears. I'd wish to not have the tags shown.
context javascript:
this.loadPage = function(page, callback){
$.get(page.ViewFile, function(view){
var content = $("#content");
$("#content").html(view);
}};
The page getting loaded contains, which is stored in the variable view as a string.
<h1>New Content</h1>
<div id="newContent"></div>
<script>
function View(){
this.InitializeView = function(model){
//code
}
this.UpdateView = function (model){
//code
}
}
</script>
Seems that the browser detect the </script> (the end of script tag) that is inside of string as a real closing when we put our code in the head of page.
This is the reason why the error is thrown in the webpage (EXAMPLE):
Uncaught SyntaxError: Unexpected token ILLEGAL fiddle.jshell.net/:22
I guess that you have to move your javascript code into a separate file like main.js, for example.
Tested it locally and it works:
HTML
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.js"></script>
<script src="main.js"></script>
<script type="text/javascript">
setTimeout(function () {
$("body").text("Testing now from HTML: using <script>");
setTimeout(function () {
$("body").html("<script>alert('This alert will fail.')</script>");
}, 1000);
}, 2000);
</script>
</head>
<body></body>
</html>
Javascript (main.js)
$(document).ready(function () {
$("body").html("<h1>Wait one second.</h1>");
setTimeout(function () {
$("body").html("<script>alert('Tested')</script>");
}, 1000);
});
Even the text editors detect it as closing tag:
Solution
1. Create scripts from jQuery
var content = $("#content");
var script = $("<script>");
script.html("alert('Testing');");
content.append(script)
1. Use &
Basically you have to replace < with &lt, > with &gt and & with &amp, as described in this answer:
var tagsToReplace = {
'&': '&',
'<': '<',
'>': '>'
};
function replaceTag(tag) {
return tagsToReplace[tag] || tag;
}
function safe_tags_replace(str) {
return str.replace(/[&<>]/g, replaceTag);
}
For more information see this question.

mousedown is not calling my function

I've created links to transition yet when the function is supposed to be called using the onmousedown event I get an uncaught undefined function. Clearly my function is defined. I'm am still learning code so what is it I don't see or understand. Any tips will be greatly appreciated.
<html>
<head>
<script type="text/javascript"src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery-ui.js"></script>
<script type="javascript">
$(document).ready(function (){
var url = "phpajaxtut.php";
});
function swapContent(cv){
$("#myDiv").html("animated gif goes here").show();
.post(url, {contentVar:cv}, function(data){
$("#myDiv").html(data).show();
});
}
</script>
Click the text
Click the text
Click the text
</head>
<body >
<div id ="myDiv">My default content</div>
</body>
</html>
Why not just use $.click(); instead, since you're already using jQuery, and forgo the hyperlinks? You can easily style some spans to look like as if that's what you want. My example just updates some text, but in there you can place / call your function.
See here:
// html
<span>Click Me</span>
<br />
<span>Click Me</span>​
// js
var n = 0;
$("span").click(function(){
$(this).text($(this).text() + " " + n++);
});​
Do you need a $ before .post?
$.post(url, {contentVar:cv}, function(data){
$(document).ready(function (){
var url = "phpajaxtut.php";
});
The var url isn't global. It can only be used inside the function
var url; //global url
$(document).ready(function (){
url = "phpajaxtut.php"; // set global url
});

Categories

Resources