Can CodeMirror 2 be used to highlight code from a DIV or PRE tag (without the editor)?
Like CodeMirror 1 used to be able to do with the hightlightText() function?
For example here: http://codemirror.net/1/highlight.html, after you press run highlight (the highlighted text below)
Also can it highlight code from a inline element, like <code>, and keep the results inline, like Google's Prettify does?
A much nicer and easier solution is to just set the readOnly property of the CodeMirror instance to true, like this:
$('.code').each(function() {
var $this = $(this),
$code = $this.html();
$this.empty();
var myCodeMirror = CodeMirror(this, {
value: $code,
mode: 'javascript',
lineNumbers: !$this.is('.inline'),
readOnly: true
});
});
Just add the class .code to the tag containing the code and it will be syntax highlighted. I've also added support for inline code, by using the class .inline.
Example on jsfiddle
As a somewhat late update, CodeMirror 2 recently gained this ability. See http://codemirror.net/demo/runmode.html
You should use a standalone code syntax highlighter: SyntaxHighlighter 3 works really well.
If you really want CodeMirror, there is a readOnly option:
var myCodeMirror = CodeMirror(function(elt) {
myElement.parentNode.replaceChild(myElement, elt); // myElement is your <pre> or <div>
}, {
value: myElement.value,
readOnly: true
});
Actually you can't. Codemirror2 is written in the way that all implementation is hidden in closures. Public methods which can be used are described in documentation http://codemirror.net/manual.html
The only available options are to use anothe syntax highlighters or dive into the code of CodeMirror2 to strip necessary parts out.
If you will chose last option, please give attention to
function refreshDisplay(from, to) method
it loops through lines and highlights them.
Edit
Just realized a simpler method exists. Read method 2 below. I'm keeping the old method and its explanations intact and just include the improved jQuery code.
If you are asking about a native method of the package, the answer is no, it only works with textarea. But if you are open to using workarounds, here is one that works (tested).
I have used jQuery here, but its use is not a must and you can achieve the same with pure js code, though it would be longer and not as neat as jQuery code.
Now, let's get to the workaround.
Suppose you have a <pre> with code inside, that you want to turn into editor-less syntax-highlighted codemirror container:
<pre id="mycode">
<?php
echo 'hi';
$a = 10;
if($a == 5) echo 'too small';
?>
</pre>
What you do is,
change the <pre> to <textarea>,
attach codemirror to the textarea,
hide the fake cursor and keep it hidden, and
do not allow the hidden codemirror's textarea grab the focus (and snatch it back when it does).
For the last action I have used the method suggested by Travis Webb. Here is the jQuery code that does these four things:
$(document).ready(function() {
// (1) replace pre with textarea
$('#mycode').replaceWith('<textarea id="code">' + $('#mycode').html() + '</textarea>');
// (2) attach codemirror
var editor = CodeMirror.fromTextArea($("#code"), {
lineNumbers: true,
mode: "application/x-httpd-php"
});
// (3) hide the fake cursor
$('pre.CodeMirror-cursor').hide();
// [4] textarea to grab and keep the focus
$('body').append('<textarea id="tricky" style="height: 1px; position: fixed; width: 1px; top: 0; margin-top: -100px;" wrap="off"></textarea>');
// (4) grab focus
$('#tricky').focus();
// [4] if focus is lost (probably to codemirror)
$('#tricky').blur(function() {
// (4) re-claim focus
$('#tricky').focus();
// (3) keep the fake cursor hidden
$('pre.CodeMirror-cursor').hide();
});
});
Method Two
Instead of wrestling with cursor and all that, we can remove the elements that make the editor tick. Here is the code:
$(document).ready(function() {
$('#mycode').replaceWith('<textarea id="code">' + $('#mycode').html() + '</textarea>');
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
mode: "application/x-httpd-php"
});
$('pre.CodeMirror-cursor').remove();
$('div.CodeMirror').find('textarea').blur().parent().remove();
$('div.CodeMirror').find('pre:first').remove();
$('textarea#code').remove();
});
CodeMirror V2 contains a runmode.js.
I've wrote an example using runmode with gutter.
check:
http://jsfiddle.net/lyhcode/37vHL/2/
Heres an simpler solution using codemirror runmode and jquery:
<pre class='code'>{:message => 'sample code'}</pre>
$(document).ready(function() {
$('.code').each(function(index, e) {
$(e).addClass('cm-s-default'); // apply a theme class
CodeMirror.runMode($(e).text(), "javascript", $(e)[0]);
});
});
Related
Never used JavaScript Before and I'm trying to fix this form in share point.
I want this text box to be small (like 1 row), until the user clicks it and then it should expand into a larger text box with like 10 rows. I apologize if this has been answered before, I don't even know what I should be looking for. Here is code I have that doesn't work, but does pop up an error message(I did not write this code):
alert(DescriptionID);
document.getElementById(DescriptionID).addEventListener("onmouseover", function(){
document.getElementById(DescriptionID).rows= "10";
});
document.getElementById(DescriptionID).addEventListener("onmouseout", function(){
document.getElementById(DescriptionID).rows= "1";
});
EDIT:
Here is what the current code will display:
EDIT2:
Thanks to a ton of help from you guys/gals I am close to finished! I can now understand it significantly better at least! Here is a picture of the code. The object is actually an "ms-formbody" ???
AND ANOTHER EDIT:
So here is the error i'm getting after using Johhny's code:
If you are using jQuery, this might work for you:
HTML:
<textarea id="expandingTextarea" rows="1">Enter Text</textarea>
JavaScript:
$(document).ready(function() {
$('#expandingTextarea').on('mouseover', function() {
$(this).attr('rows', '10');
});
$('#expandingTextarea').on('mouseout', function() {
$(this).attr('rows', '1');
});
});
I created an example here.
Update:
Using a click event to change/toggle to row count:
$(document).ready(function() {
$('#expandingTextarea').on('click', toggleExpand);
function toggleExpand() {
var oldRowCount = $(this).attr('rows');
var newRowCount = parseInt(oldRowCount) === 1 ? 10 : 1;
$(this).attr('rows', newRowCount);
}
});
Demo here.
In fact, you don't need JS to achieve what you want. CSS can do it for you.
<!--html-->
<textarea class="descr">This is description</textarea>
/*css*/
.descr {height: 20px;}
.descr:hover, .descr:focus {height: 120px;}
alter the height instead of the "rows" property.
open up the page in chrome, open the developer tools (View->Developer->Developer Tools) and then use "inspect" to select the text area you want to manipulate.
try playing around with the css of that element. then, write your javascript to change just the property that you want.
https://developer.chrome.com/devtools
The code you showed looks fine but DescriptionID should contain the ID of the description box. You can check what it is by right clicking on the description form and clicking "inspect element". Then assign var DescriptionID = "someID" at the beginning of the code.
Also, you might consider altering the height, not the rows.
If the form doesn't have an ID, look for an option to change the HTML and add one. If you don't have such an option, it's still possible to achieve what you want to do but you have to look beyond getElementById.
I'm doing a fancy comment list on my project, structured like this:
As you see, there's a comments list and at his bottom there's an input field (textarea) to submit a comment. Note that there's the current username attached to the right (let's call it a simple static appended text).
I just found this little JS to make an input field resize automatically by adapting it to the content.
function resizeInput() {
$(this).attr('size', $(this).val().length);
}
$('input[type="text"]').keyup(resizeInput).each(resizeInput);
But it's not enough. I need it for a textarea and I want it to behave correctly when a comment is long enough to wrap on another line. By definition, the input field is a box, and it obviously acts badly compared to what I want:
Instead, this should be the right behavior:
I looked everywhere and I can't think any way to implement this. Can somebody help me?
Here is a good plugin for textarea. But it using jQuery.
usage simple as always.
$(document).ready(function(){
$('textarea').autosize();
});
You could use the contenteditable attribute:
<span contenteditable="true">comment</span> by <span class="userName">someone</span>
It is supported in practically all browsers. Using the right CSS, you can underline the content and also limit the width.
I think you mean this
NOTE: No check for selection and bound to document. Exercise for the reader to bind to a specific field and swap it for a span
FiDDLE
$(document).keypress(function(e) {
var char = String.fromCharCode(e.which);
if (e.which==13) char = '<br/>'; // needs to handle backspace etc.
$("#textfield").append(char);
$("#hiddenfield").val($("#textfield").text()); // or .html if you want the BRs
e.preventDefault();
});
using
<span id="textfield"></span> - by My Username
If you make the field contenteditable you will get this in Chrome so some additional CSS may be needed
Use a <span> with contenteditable (supported in IE too). Here is a fiddle: http://jsfiddle.net/goabqjLn/2/
<span contenteditable>Insert a comment...</span> by My Username
Then, using JavaScript, attach an event listener that mirrors the inner text of the span into a hidden input field, so it gets submitted with your <form>.
Edit: I have updated the fiddle to also include the JS code. Here is the updated code:
<span class="editor" id="editor" contenteditable data-placeholder="Insert a comment...">Insert a comment...</span> by My Username
<!-- Hide this textarea in production: -->
<textarea type="text" id="comment"></textarea>
And the JS:
function mirror() {
var text = $('#editor').html().trim()
.replace(' ', ' ')
.replace(/<br(\s*)\/*>/ig, '\n') // replace single line-breaks
.replace(/<[p|div]\s/ig, '\n$0') // add a line break before all div and p tags
.replace(/(<([^>]+)>)/ig, ""); // remove any remaining tags
$('#comment').val(text);
}
$('#editor').focus(function () {
var editor = $(this);
if (editor.text() == editor.attr('data-placeholder')) {
editor.text('');
}
}).blur(function () {
var editor = $(this);
if (editor.text() == editor.attr('data-placeholder')) {
editor.text(editor.attr('data-placeholder'));
}
}).blur(mirror).keyup(mirror);
I'm building a search by tags input box as seen here:
http://jsfiddle.net/Newtt/7nUAf/
Forgive the terrible styling as this is just a small component of a larger application and I've just added the styles needed to show my issue.
My search box is a div that has it's text inserted using Jquery as follows:
$(document).ready(function () {
$('.search-box').click(function () {
$('.search-options').toggle();
});
$('.options').click(function () {
var d = $('.search-box').html();
console.log(d);
var c = $(this).html();
console.log(c);
if (d != '') {
$('.search-box').html(d + ', ' + c);
} else {
$('.search-box').html(c);
}
$('.search-options').hide();
});
$('#reset').click(function () {
$('.search-box').html('');
});
});
where .search-box is the input div, .options are the clickable options from the drop down box search-options.
Currently, the text of each option is inserted into the search-box div. I need this to be styled dynamically while it enters the search box.
I tried something on the lines of:
$('<span>').addClass('tag').append(
$('<span>').text(value).append(' '),
$('<a>', {
href : '#',
title : 'Removing tag',
text : 'x'
});
where the tag class is defined in the style sheet to style the element to look like a tag,
but this doesn't work at all. Can someone help me out with how to achieve styling the input text to look like a tag from, say, Evernote notebooks?
Thanks!
I adapted your fiddle. Just wrap c in a span with a class (like you were trying to do in the second part of your post) and apply styles in css. I have just made the background red, but it should be easy enough to make it look like a tag like the ones in the drop down do.
http://jsfiddle.net/7nUAf/1/
JS:
$('.options').click(function () {
var d = $('.search-box').html();
var c = $(this).html();
$('.search-box').append('<span class="tag">'+c +'</span>');
$('.search-options').hide();
});
CSS:
.tag {
background: red;
}
For what you are looking to do - there are lots of excellent plug ins already available that provide much "prettier" functionality and with much less work on your part. Some have already been suggested in the comments - I might suggest consider using "chosen". The syntax is amazingly simple. Just create a select box as follows:
<select id="test" multiple>
<option>pdf</option>
<option>document</option>
</select>
Then in your document ready function you simply need to call chosen plugin:
$(document).ready(function () {
$('#test').chosen({width: "80%"});
});
I put together an example that does this on JSFiddle here: http://jsfiddle.net/7nUAf/3/. Once you get to the point that you have it working you can easily style the elements by inspecting what elements chosen is creating. For example the "li.search-choice" selector will allow you to style the selected items.
In General - even if you don't like this particular plug in, always consider running a search for existing items that do what you are looking for. In the case that these aren't perfect you can always improve them and provide that insight back to the community as a whole. In that way, everyone learns together.
Best of luck!
I am currently trying to add an inline ckeditor to some text.
No javascript errors occour but unfortunately all tools are disabled and I can't edit the text.
http://fiddle.jshell.net/5LuyD/
Any one have a clue as to what I am doing wrong?
What you're missing is contenteditable="true" attribute for your element. If you want to have the editor customized (i.e. ran via CKEDITOR.inline( element, cfg )), set CKEDITOR.disableAutoInline = true; first.
With CKEDITOR.disableAutoInline = true;, all the contenteditable="true" elements must be initialized manually to become an editor instance. See the official guide for inline instances.
You missed the contenteditable="true" attribute for the tags that are editable!
Here is the fiddle. http://fiddle.jshell.net/5LuyD/1/
For anyone having this issue despite setting contenteditable="true", there is an issue with Chrome where contenteditable is set to false if the element (or parent element) is not visible.
See: http://ckeditor.com/forums/CKEditor/Solved-Chrome-Toolbar-buttons-grayed-out-for-INLINE-editor
The solution is to either a) ensure the element is visible before calling CKEDITOR.inline() or b) use a textarea instead of a contenteditable element (CKE adds a contenteditable div after the textarea in this case).
I just had the same issue and I discovered a different fix for it. If the parent element (or the element itself) is originally set to display:none the contenteditable will = false (on chrome).
This fix worked for me:
var ck = CKEDITOR.inline(element);
ck.on('instanceReady', function(event) {
var editor = event.editor;
editor.setReadOnly(false);
});
Ref: https://dev.ckeditor.com/ticket/9814
I had the same problem and none of the other suggested solutions worked.
The problem was that the id attribute of the div started with a numeric character (it was a GUID). Changing the id to begin with an alpha character worked: all the editor buttons were enabled.
For some reason, ckEditor doesn't like id's that begin with numeric characters.
$(document).ready(function(){
for(var i in CKEDITOR.instances) {
var ck=CKEDITOR.instances[i];
ck.on( 'instanceReady', function( ev ) {
var editor = ev.editor;
editor.setReadOnly( false );
});
}});
I want to achieve a python version web regexbuddy,and i encounter a problem,how to highlight match values in different color(switch between yellow and blue) in a textarea,there has a demo what exactly i want on http://regexpal.com,but i was a newbie on js,i didn't understand his code meaning.
any advice is appreciated
To save time you should consider using an existing library for this requirement.
Quote from here:
As textarea elements can’t render HTML, this plugin allows you to highlight text inside textarea elements.
jQuery highlightTextarea.
Demo: Codepen
Usage:
$context.highlightTextarea(options);
There is a pre element over the textarea. So when you type anything it is copying the input on the pre element, applying some filters.
For example:
<pre id="view"></pre>
<textarea id="code"></textarea>
When you type on #code it is copying the value, applying filters and adding the HTML to the #view.
var code = document.getElementById("code");
var pre = document.getElementById("pre");
(code).onkeyup = function (){
val = this.value;
val = YourRegex(val);
(pre).innerHTML = val;
};
YourRegex would be a method to match the regex and return some parsed content to the pre, allowing you to customize the appearance of the textarea (that is actually an element over it).
function YourRegex(val)
{
// This function add colors, bold, whatever you want.
if (/bbcc/i.test("bbcc"))
return "<b>" + val + "</b>";
}
#BrunoLM's solution is excellent, but might require more hacking than you're comfortable with. If you're interested (and if jQuery is already in your stack), the following plugin may be worth taking a look at:
http://garysieling.github.io/jquery-highlighttextarea/