Using <br> instead of <p> in Summernote? - javascript

Needed to use <br> tag in the summernote editor instead of <p> while user clicks on the Enter button, so here is my code:
var $this = $(this),
box = $('textarea.CommentsFields');
box.summernote({
height: 100,
focus: true,
toolbar: [
[ 'all', [ 'bold', 'strikethrough', 'ul', 'ol', 'link' ] ],
[ 'sided', [ 'fullscreen' ] ]
],
callbacks: {
onEnter: function(){
box.summernote('insertNode', document.createTextNode("<br>"));
console.log('uiwdbvuwecbweuiuinsjk');
}
}
});
I wrote a custom callback of the onEnter event, when the user hit the return button it raises a callback, and write the <br> tag which is not what I am looking for.
I read their documentation but can not understand how to stop the default action of the enter button and write <br> tag instead of wrapping the element in <p> tag.
Any idea? Thanks

This code worked for me:
$("#summernote").on("summernote.enter", function(we, e) {
$(this).summernote("pasteHTML", "<br><br>");
e.preventDefault();
});
This interceps the Enter press event and changes its default behaviour, inserting a <br> instead of a new paragraph.

If you don't want to change or fix the summernote library itself, you can use the shortcut keys for adding a line break.
Use Shift + Enter for giving a line break.
Use Enter for changing a paragraph, as summernote add a div/p to start a new line when you press Enter.
Hope this works.

There appear to be at least 10 or so bugs filed about this over at SummerNote, with no fix or plan to fix it unfortunately.
Fortunately you can fix it in a sneaky way, that is going to be pretty brittle to future versions - so upgrade carefully. You Monkey Patch it:
$.summernote.dom.emptyPara = "<div><br/></div>";
box.summernote(options);
The first line is the fix - the Monkey Patch. I included the second line, where SummerNote is initialized, just to demonstrate you MUST do your Monkey Patch before you start SummerNote - or the Monkey Patch will not make it in and you'll still get p tags on enter.

Guaranteed 2 liner & no plugin:
$.summernote.dom.emptyPara = "<div><br></div>"; // js
.note-editor .note-status-output{display:none;} /*css*/

Today summernote has no way to do what you want. You can check https://github.com/summernote/summernote/issues/702, so, the only way is to create your own pull-request with fixed logic for different paragraph style.

This worked for me
Replace (in Summernote.js line 3786)
if (event.keyCode === key.code.ENTER) {
context.triggerEvent('enter', event);
}
in
if (event.keyCode === key.code.ENTER) {
return;
}

I encountered this problem and the solution is below.
onKeydown function in callbacks solves your problems.
Example:
$('.textarea-editor').summernote({
height: 250, // set editor height
minHeight: null, // set minimum height of editor
maxHeight: null, // set maximum height of editor
focus: true, // set focus to editable area after initializing summernote
htmlMode: true,
lineNumbers: true,
codemirror: { // codemirror options
theme: 'monokai'
},
mode: 'text/html',
callbacks: {
onKeydown: function(e) {
e.stopPropagation();
}
}
});

Related

Add a custom button to the Quill's toolbar (and integrate it also on the PrimeFaces Text Editor)?

I am using PrimeFaces 7 and its TextEditor component, which uses internally the free and open-source editor Quill
I need to add a custom HTML button, which, when selected, inserts the word selected on the current position of the cursor in the TextEditor - (in the Quill)
It is possible to add custom buttons in the Quill Editor and to attach EventListeners to them, as shown here:
https://quilljs.com/docs/modules/toolbar/
(Please look at this part of the above page):
var customButton = document.querySelector('#custom-button');
customButton.addEventListener('click', function() {
console.log('Clicked!');
});
There is also an API provided by the Quill editor to insert text at a given position, see here:
https://quilljs.com/docs/api/#content
have a look at this mehod:
`quill.insertText(0, 'Hello', 'bold', true);`
However, I do miss a couple of things:
1.) The definition of the custom-button shall be done in the toolbar div, as specified in the following code:
`<div id="toolbar">
<!-- But you can also add your own -->
<button id="custom-button"></button>`
However: how could I do that, when using ready PrimeFaces Text Editor component?
I locally tried this:
jQuery(document).ready(function () {
jQuery(document).ready(function () {
var customButton = document.getElementById("resultsFormId:quillToolbarId_toolbar:custButId");
if (customButton!=null){
return;
}
customButton = document.createElement("button");
customButton.innerHTML = 'Params';
customButton.id="resultsFormId:quillToolbarId_toolbar:custButId";
var qlTollbar = document.getElementById("resultsFormId:quillToolbarId_toolbar");
qlTollbar.appendChild(customButton);
customButton.addEventListener('click', function() {
Quill.insertText(0, 'Hello', 'bold', true);
console.log('Clicked!');
});
});
});
and could say the following:
1.1) The custom button gets inserted on the Quill toolbar (is not nice and styled, but it is there)
1.2) When I click the custom button, first the EventListener gets executed. This is OK,but here:
Quill.insertText(0, 'Hello', 'bold', true);
instead of Quill.insertText()., I need a reference to the js-object representing the Quill editor. === > Could you help?
1.3) after the EventListener from Point (1.2) gets executed, my whole code under
jQuery(document).ready(function () {
jQuery(document).ready(function () {
gets executed once again, the id of the customButton is not found, and it is recreated once again. ===> Could I avoid that?
2.) In the code for the insertion of a text on a specific position, I need to get the last position the cursor was, before the user clicked (selected the option on the) custom button.
How can I do that?
I never heard of PrimeFaces, but maybe I can answer this part of you question:
Quill.insertText(0, 'Hello', 'bold', true);
instead of Quill.insertText()., I need a reference to the js-object representing the Quill editor. === > Could you help?
According to the code on GitHub it should be
PrimeFaces.widget.TextEditor.editor.insertText(0, 'Hello', 'bold', true)
can you confirm? Then you should also be able to get the cursor location and selection (if any) with
PrimeFaces.widget.TextEditor.editor.getSelection();

Remove word-wrap offset in ACE editor

I need to remove offseting 4 " " which are automatically created after breaking line in ACE editor
I tried using editor.setTabSize(0) that worked as well, but then I can't ident code by using TAB, as it throws "undefined" instead into code. I searched on ACE webpage, but there is nothing as that, and when searched forums, it told something with setBehaviosrEnabled, but that didn't work either
Any idea how to get rid of those 4 spaces?
Issue:
Code:
var editor = ace.edit("edittext");
editor.setOptions({
maxLines: Infinity
});
editor.getSession().setUseWrapMode(true);
editor.setBehavioursEnabled(false);
editor.renderer.setOption('showLineNumbers', false);
editor.setTheme("ace/theme/xcode");
This is controlled by indentedSoftWrap setting in ace, you cn turn it off by running
editor.setOption("indentedSoftWrap", false);
behaviours setting is completely unrelated and controls automatic insertion of closing brackets and tags.
So your code from the above would become
var editor = ace.edit("edittext");
editor.setOptions({
maxLines: Infinity, // this is going to be very slow on large documents
useWrapMode: true, // wrap text to view
indentedSoftWrap: false,
behavioursEnabled: false, // disable autopairing of brackets and tags
showLineNumbers: false, // hide the gutter
theme: "ace/theme/xcode"
});

HTML form doesnt allow spaces on inputs

I have an HTML form loaded in via ajax to a lightbox.
You can see the behaviour on the homepage of http://www.powerbuy.com.au/
In the bottom right of the page there is a Link 'Let us negotiate a deal for you' Clicking this creates a lightbox and loads the form.
The issue is that you cannot put in spaces to any of the fields, it appears to be accepting any other characters, numbers and symbols, but not spaces.
I have looked through the code for any keyCode in the JS, but I cant find anything related to spaces.
Can you replicate the issue? Can you tell me what is going on?
You can simply write below code:
$(document).ready(function(){
$("#id").keydown(function(event) {
if(event.shiftKey)
{
event.preventDefault();
}
if (event.keyCode == 32) {
event.preventDefault();
}
});
});
"id" is your textfield "id" attribute value.
Cause unknown:
Solved by converting lightbox popup from ajax load to iframe.
You can fix it by setting enableKeys : false as following:
Shadowbox.open({
title : "Nouvel Addressee",
content : $("addressee-lightbox-wrapper").innerHTML,
player : "html",
width : 920,
height : 540,
enableKeys : false,
options : {
onFinish: function() {
Event.addBehavior.reload();
}
}
});
I had similar problem. Found out, it has something with 'enableKeys' option.
There is more ways to set this option, but for some reason just this one worked for me:
Shadowbox.init({
skipsetup: true,
enableKeys: false
});
Here are some other solutions mentioned http://shadowbox.1309102.n2.nabble.com/Can-t-add-space-in-text-input-td4518072.html

Javascript Fancybox 1.3.4 Solution but needed it further explained please

This answer has been taken from this post:
Fancybox problem on iPhone
This was voted as best answer but I am new and still learning at js and I am having such a difficult time putting this all together, can someone help me with some more detailed instructions?
Fancybox attempts to auto resize and center itself everytime that the
browser window is resized, and this event gets triggered a lot on
iPads and iPhones. For fancy box 1.3.4, the code which controls this
is line 608: $(window).bind("resize.fb", $fancybox.resize);
To fix the issue, I modified this part of the fancybox JS, and added
another option called "resizeOnWindowResize", which you can set to
false for iPad and iPhone users, or just disable all together.
if(currentOpts.resizeOnWindowResize) { $(window).bind("resize.fb",
$fancybox.resize); } You must also add a default value for this
option in $.fn.fancybox.defaults hash map.
Then, when calling fancybox you can utilize this new option:
$('#fancybox_link').fancybox(${'scrolling': 'no',
width: 'auto',
height: 'auto',
centerOnScroll: false,
resizeOnWindowResize : false});
I got as far as go to line 608. I really do not know what to do next. What should the final product look like after you've added "resizeonwindowResize" and the if statement?
Add this:
if(currentOpts.resizeOnWindowResize) {
$(window).bind("resize.fb", $.fancybox.resize);
}
Where you find:
$(window).bind("resize.fb", $.fancybox.resize);
Near the bottom of:
$.fn.fancybox.defaults = { //blah blah blah options here.
onComplete : function(){},
onCleanup : function(){},
onClosed : function(){},
onError : function(){},
// Add this
resizeOnWindowResize: true
};
Then save and when you call the fancybox:
$('.photo_gallery a').fancybox({
resizeOnWindowResize: false
});
This is also an alternative. Just replace the $.fancybox.resize function to as follows. It's just adding a simple userAgent check to avoid the .center call for iPhones.
$.fancybox.resize = function() {
if (overlay.is(':visible')) {
overlay.css('height', $(document).height());
}
if(!(navigator.userAgent.match(/iPhone/i)) && !(navigator.userAgent.match(/iPod/i))) {
$.fancybox.center(true);
}
};

Codemirror editor is not loading content until clicked

I am using codemirror 2 and its working fine except that the editor's set value doesn't load into the editor until I click the editor and it becomes focused.
I want the editor to show the content of itself without it having to be clicked. Any ideas?
All of the codemirror demos work as expected so I figured maybe the textarea isn't focused so I tried that too.
$("#editor").focus();
var editor = CodeMirror.fromTextArea(document.getElementById("editor"), {
mode: "text/html",
height: "197px",
lineNumbers: true
});
You must call refresh() after setValue(). However, you must use setTimeout to postpone the refresh() to after CodeMirror/Browser has updated the layout according to the new content:
codeMirrorRef.setValue(content);
setTimeout(function() {
codeMirrorRef.refresh();
},1);
It works well for me. I found the answer in here.
Just in case, and for everyone who doesn't read the documentation carefully enough (like me), but stumbles upon this.
There's an autorefresh addon just for that.
You need to add autorefresh.js in your file.
Now you can use it like this.
var editor = CodeMirror.fromTextArea(document.getElementById("id_commentsHint"), {
mode: "javascript",
autoRefresh:true,
lineNumbers: false,
lineWrapping: true,
});
works like a charm.
I expect you (or some script you loaded) is meddling with the DOM in such a way that the editor is hidden or otherwise in a strange position when created. It'll require a call to its refresh() method after it is made visible.
I happen to be using CodeMirror within a bootstrap tab. I suspected the bootstrap tabs were what was preventing it from showing up until clicked. I fixed this by simply calling the refresh() method on show.
var cmInstance = CodeMirror.fromTextArea(document.getElementById('cm'), {
lineNumbers: true,
lineWrapping: true,
indentUnit: 4,
mode: 'css'
});
// to fix code mirror not showing up until clicked
$(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function() {
this.refresh();
}.bind(cmInstance));
Something worked for me.
$(document).ready(function(){
var editor = CodeMirror.fromTextArea(document.getElementById("code2"), {
//lineNumbers: true,
readOnly: true,
autofocus: true,
matchBrackets: true,
styleActiveLine: true
});
setTimeout(function() {
editor.refresh();
}, 100);
});
The 5.14.2 version of codemirror addresses this fully with an add on. See this answer for details.
I am working with react, and all these answers did not work with me...After reading the documentation it worked like this:
in the constructor, I initialized an instance of code Mirror:
this.mirrorInstance = null;
and on opening the tab that contains the codeEditor, I refreshed the instance after 1 millisecocnd:
toggleSubTab() {
setTimeout(() => {
this.mirrorInstance.refresh();
}, 1);
}
and here is the JSX code:
<CodeMirror
value={this.state.codeEditor}
options={{
mode: "htmlmixed",
theme: "default",
lineNumbers: true,
lineWrapping: true,
autoRefresh: true
}}
editorDidMount={editor => {
this.mirrorInstance = editor;
}}
/>
I just ran into a version of this problem myself this evening.
A number of other posts regard the visibility of the textarea parent as being important, if it's hidden then you can run into this problem.
In my situation the form itself and immediate surroundings were fine but my Backbone view manager higher up the rendering chain was the problem.
My view element isn't placed on the DOM until the view has rendered itself fully, so I guess an element not on the DOM is considered hidden or just not handled.
To get around it I added a post-render phase (pseudocode):
view.render();
$('body').html(view.el);
view.postRender();
In postRender the view can do what it needs knowing that all the content is now visible on the screen, this is where I moved the CodeMirror and it worked fine.
This might also go some of the way to explain also why one may run into problems with things like popups as in some cases they may try to build all content before displaying.
Hope that helps someone.
Toby
Yet another solution (which I also realised was because the editor needed to be visible to create properly) is to temporarily attach the parent element to the body element during construction, then reattach once complete.
This way, you don't need to meddle with elements, or worry about visibility in any existing hierarchies that your editor might be buried.
In my case, for processr.com, I have multiple, nested code editing elements, all of which need to be created on the fly as the user makes updates, so I do the following:
this.$elements.appendTo('body');
for (var i = 0; i < data.length; i++)
{
this.addElement(data[i]);
}
this.$elements.appendTo(this.$view);
It works great, and there's been no visible flicker or anything like that so far.
Try calling focus on the DOM element instead of the jQuery object.
var editor=$( '#editor' );
editor[0].focus();
// or
document.getElementById( 'editor' ).focus();
<div class="tabbable-line">
<ul class="nav nav-tabs">
<li class="active">
Xml 1
</li>
<li class="">
Xml 2
</li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="tabXml1">
<textarea id="txtXml1" />
</div>
<div class="tab-pane" id="tabXml2">
<textarea id="txtXml2" />
</div>
</div>
</div>
<link rel="stylesheet" href="~/Content/codemirror.min.css">
<style type="text/css">
.CodeMirror {
border: 1px solid #eee;
max-width: 100%;
height: 400px;
}
</style>
<script src="~/Scripts/codemirror.min.js"></script>
<script src="~/Scripts/codemirror.xml.min.js"></script>
<script>
$(document).ready(function () {
var cmXml1;
var cmXml2;
cmXml1 = CodeMirror.fromTextArea(document.getElementById("txtXml1"), {
mode: "xml",
lineNumbers: true
});
cmXml2 = CodeMirror.fromTextArea(document.getElementById("txtXml2"), {
mode: "xml",
lineNumbers: true
});
// Refresh code mirror element when tab header is clicked.
$("#xmlTab2Header").click(function () {
setTimeout(function () {
cmXml2.refresh();
}, 10);
});
});
</script>
Something worked for me! :)
var sh = setInterval(function() {
agentConfigEditor.refresh();
}, 500);
setTimeout(function(){
clearInterval(sh);
},2000)
using refresh help solve this problem. But it seems not friendly
The reason:
CodeMirror won't update DOM content when it's DOM Node is unvisible.
For example:
when the CodeMirror's Dom is setted style to 'display: none'.
The way to fix:
when CodeMirror's Dom is visible, manual excute the cm.refresh() method.
For example in my application, the CodeMirror Dom will visible when the tab element clicked.
So the simple method is:
window.onclick = () => {
setTimeout(() => {
codeMirrorRef.refresh();
}, 10);
};
You can add event listener on more specific element to improve the performance.
chain this to the master codemirror object, make sure that nothing else is chained
.on('change', editor => {
globalContent = editor.getValue();
});;

Categories