Add hanging indent to CKEditor on web page [duplicate] - javascript

I'm using CKEditor and I want to indent just the first line of the paragraph. What I've done before is click "Source" and edit the <p> style to include text-indent:12.7mm;, but when I click "Source" again to go back to the normal editor, my changes are gone and I have no idea why.
My preference would be to create a custom toolbar button, but I'm not sure how to do so or where to edit so that clicking a custom button would edit the <p> with the style attribute I want it to have.

Depending on which version of CKE you use, your changes most likely disappear because ether the style attribute or the text-indent style is not allowed in the content. This is due to the Allowed Content Filter feature of CKEditor, read more here: http://docs.ckeditor.com/#!/guide/dev_advanced_content_filter
Like Ervald said in the comments, you can also use CSS to do this without adding the code manually - however, your targeting options are limited. Either you have to target all paragraphs or add an id or class property to your paragraph(s) and target that. Or if you use a selector like :first-child you are restricted to always having the first element indented only (which might be what you want, I don't know :D).
To use CSS like that, you have to add the relevant code to contents.css, which is the CSS file used in the Editor contents and also you have to include it wherever you output the Editor contents.
In my opinion the best solution would indeed be making a plugin that places an icon on the toolbar and that button, when clicked, would add or remove a class like "indentMePlease" to the currently active paragraph. Developing said plugin is quite simple and well documented, see the excellent example at http://docs.ckeditor.com/#!/guide/plugin_sdk_sample_1 - if you need more info or have questions about that, ask in the comments :)
If you do do that, you again need to add the "indentMePlease" style implementation in contents.css and the output page.

I've got a way to indent the first line without using style, because I'm using iReport to generate automatic reports. Jasper does not understand styles. So I assign by jQuery an onkeydown method to the main iframe of CKEditor 4.6 and I check the TAB and Shift key to do and undo the first line indentation.
// TAB
$(document).ready(function(){
startTab();
});
function startTab() {
setTimeout(function(){
var $iframe_document;
var $iframe;
$iframe_document = $('.cke_wysiwyg_frame').contents();
$iframe = $iframe_document.find('body');
$iframe.keydown(function(e){
event_onkeydown(e);
});
},300);
}
function event_onkeydown(event){
if(event.keyCode===9) { // key tab
event.preventDefault();
setTimeout(function(){
var editor = CKEDITOR.instances['editor1'], //get your CKEDITOR instance here
range = editor.getSelection().getRanges()[0],
startNode = range.startContainer,
element = startNode.$,
parent;
if(element.parentNode.tagName != 'BODY') // If you take an inner element of the paragraph, get the parentNode (P)
parent = element.parentNode;
else // If it takes BODY as parentNode, it updates the inner element
parent = element;
if(event.shiftKey) { // reverse tab
var res = parent.innerHTML.toString().split(' ');
var aux = [];
var count_space = 0;
for(var i=0;i<res.length;i++) {
// console.log(res[i]);
if(res[i] == "")
count_space++;
if(count_space > 8 || res[i] != "") {
if(!count_space > 8)
count_space = 9;
aux.push(res[i]);
}
}
parent.innerHTML = aux.join(' ');
}
else { // tab
var spaces = " ";
parent.innerHTML = spaces + parent.innerHTML;
}
},200);
}
}

Related

Trying to create new custom HTML elements which perform action in JQuery

I am trying to create my own custom HTML elements where a user can interact with the text within that element. For Example, I created an element where anything between those tags will have a pointer as a mouse cursor and when double clicked, something happens. EG:
<objdc>Double click me!</objdc>
However, this is my code and it is not working:
$(document).ready(function() {
var ObjDblClk = $('objdc');
ObjDblClk.css({ cursor: 'pointer' });
ObjDblClk.dblclick(function(e) {
var range = window.getSelection() || document.getSelection() || document.selection.createRange();
var word = $.trim(range.toString());
if(word != '') {
//Do Something
}
range.collapse();
e.stopPropagation();
});
});
}
Any suggestions?
The problem you have is related with the fact you are not using the collapse method right. It expects a node as parameter and an offset.
So... to fix that exact behavior you posted you would need to do something like:
ObjDblClk.dblclick(function(e) {
var range = window.getSelection() || document.getSelection() || document.selection.createRange();
var word = $.trim(range.toString());
if(word != '') {
//Do Something
}
range.collapse(ObjDblClk[0], 0);
e.stopPropagation();
});
BUT (and this is important): That will do absolutely nothing for your custom selection (especially since is on double click witch affects selection). So you can just remove that line completely and try another solution.
Also: You should read the comments. The guys are right. Unless you are working on some reall strange inhouse thing there may be better aproaches.
Fiddle here (added an alert so you see the function is called - don't forget to select something before double clicking): https://jsfiddle.net/713ndkm0/1/
To create a custom tag like that, you have to be aware of certain things:
Not all browsers will understand your custom tag as a DOM object. IE is a notable example.
Your new custom tag should have a hyphen in it, like obj-dc (more info).
If you want to use it in IE, you have to declare it up-front, as:
document.createElement('obj-dc');
Here is a link to creating new HTML tags for Chrome, in the new way, and here is a link for the older API. As you can see, even the same browser cannot operate with custom tags consistently.

Format text as user inputs in a contenteditable div

I'm attempting to make a page that allows users to input text and it will automatically format the input -- as in a screenplay format (similar to Amazon's StoryWriter).
So far I can check for text with ":contains('example text')" and add/remove classes to it. The problem is that all of the following p tags inherit that class.
My solution so far is to use .next() to remove the class I added, but that is limited since there might be need for a line break in the script (in dialogue for instance) and that will remove the dialogue class.
$('.content').on('input', function() {
$("p.input:contains('INT.')").addClass("high").next(".input").removeClass("high");
$("p.input:contains('EXT.')").addClass("high").next(".input").removeClass("high");
});
I can't get || to work in the :contains parameter either, but that's the least of my issues.
I have a JS fiddle
I've worked on this for a while now, and if I could change only the node that contains the text (INT. or EXT. in this example) and leaves the rest alone that would work and I could apply it to the rest of the script.
Any help would be appreciated, I'm new to the stackoverflow so thank you.
See the comments in the code below for an explanation of what's going on.
Fiddle Example
JQuery
var main = function(){
var content = $('.content');
content.on('input', function() {
$("p.input").each(function() {
//Get the html content for the current p input.
var text = $(this).html();
//indexOf will return a positive value if "INT." or "EXT." exists in the html
if (text.indexOf('INT.') !== -1 || text.indexOf('EXT.') !== -1) {
$(this).addClass('high');
}
//You could include additional "if else" blocks to check and apply different conditions
else { //The required text does not exist, so remove the class for the current input
$(this).removeClass('high');
}
});
});
};//main close
$(document).ready(main);

changing cssRules with javascript is not permanent on client, getting wiped out after partial post back

I generated some css from database values on Page_Load and Then wrapped it like-
CssDiv.InnerHtml = "<style id=\"main_styles\" type=\"text/css\">\n" + {Css as string} + "\n</style>"
here CssDiv is like-
<div id="CssDiv" runat="server"></div>
user are allowed to change these css values with color pickers and drop downs. on change of picker or dropdown, I am making ajax call with the selected value to server, saving it into database. Now on success of this request, I have to change the content of $("style#main_styles") according to user's selection.
The problem is
1) When I am changing the Css its being reflected on the page but not under developer tool (that open when you right click to Inspect element). For example assume following css-
#zoneBody .blocktextContent {
background-color: #99daee;
}
now user selected #1066cc from the picker, when my code runs #1066cc is being applied on the element "#zoneBody .blocktextContent" on page but when I am inspecting the element in the developer console its still showing-
#zoneBody .blocktextContent {
background-color: #99daee; // while it should be- "background-color: #1066cc;"
}
2) The changes I made are not permanent on browser, i.e. when any other element on Page is causing partial post-back, although I am not touching CssDiv on server yet its resetting the users selection.
(I have an update panel, that wraps complete page content, even CssDiv... This is causing partial post-backs).
I am using following code to apply the user's selection-
var layoutelement= "#zoneBody .blocktextContent";
var style = "background-color";
var stylevalue= "#1066cc"; // user's selection
var sheets = document.styleSheets;
for (var i = 0; i < sheets.length; i++) {
var sheet = sheets[i];
if (sheet.ownerNode.id == "main_styles") {
var rules = sheet.cssRules;
for (var j = 0; j < rules.length; j++) {
var rule = rules[j];
if (rule.selectorText == layoutelement) {
rule.style.setProperty(style, stylevalue);
// I also tried "rule.style[style] = stylevalue;"
break;
}
}
break;
}
}
I can not use-
$(layoutelement).css(style, stylevalue);
because layoutelement can be more complex like-
layoutelement = "#zoneBody .blockTextContent a,#zoneBody .blockTextContent a:link,#zoneBody .blockTextContent a:visited,#zoneBody .blockTextContent a .yshortcuts";
I hope I am clear enough, but if you need any more description.. let me know in comments.. Thank you
Instead of changing the values of the styles, why not write the styles down in advance, and just toggle the element's classes? You can use jQuery addClass, removeClass and toggleClass if you want. Much more practical than fiddling with the CSS style definitions themselves.
For problem 1, the issue is probably that the developer tool (or view within the developer tool) you are using does not show applied styles, but simply the rules in the style sheet that match that element based on the selector. Or, in other words, it only shows the css rules in the style sheet that apply to the element you are inspecting. To see the styles that are applied at a given time, you will need to examine the styles by inspecting the element in the DOM or use javascript and the CSSStyleDeclaration object returned by getComputedStyle.

Targeting specific row/line of textarea and appending that row

I want to be able to click on a specific element, and have it send a value to a textarea. However, I want it to append to a specific row/line of the textarea.
What I am trying to build is very similar to what happens when you click the notes of the fret board on this site: http://www.guitartabcreator.com/version2/ In fact, i want it almost exactly the same as this.
But right now I am really just trying to see how I can target the specific row, as it seems doable based on this website.
Currently I am using javascript to send a value based on clicking a specific element.
Here is the js:
<script type="text/javascript">
function addNote0(text,element_id) {
document.getElementById(element_id).value += text;
}
</script>
This is the HTML that represents the clickable element:
<td> x </td>
This is the textarea:
<textarea rows="6" cols="24" id="tabText" name="text">-
-
-
-
-
-</textarea>
This works fine for sending the value. But it obviously just goes to the next available space. I am a total newb when it comes to javascript, so I am just not sure where to begin with trying to target a specific line.
What I have currently can be viewed here: http://aldentec.com/tab/
Working code:
After some help, here is the final code that made this work:
<script>
function addNote0(text,element_id) {
document.getElementById(element_id).value += text;
var tabTextRows = ['','','','','',''];
$('td').click(function(){
var fret = $(this).index() - 1;
var line = $(this).parent().index() -1;
updateNote(fret, line);
});
function updateNote(fret, line){
var i;
for(i=0;i<tabTextRows.length;i++){
if(i == line) tabTextRows[i]+='-'+fret+'-';
else tabTextRows[i]+='---';
$('#tabText').val(tabTextRows.join('\n'));
}
}}
window.onload = function() {
addNote0('', 'tabText');
};
</script>
Tried to solve this only in JS.
What I did here is use an array to model each row of the textfield (note the array length is 6).
Then I used a jQuery selector to trigger any time a <td> element is clicked which calculates the fret and string that was clicked relative to the HTML tree then calls the updateNote function. (If you change the table, the solution will probably break).
In the update note function, I iterate through the tabTextRows array, adding the appropriate note. Finally, I set the value of the <textarea> to the array joined by '\n' (newline char).
Works for me on the site you linked.
This solution is dependant on jQuery however, so make sure that's included.
Also you should consider using a monospaced font so the spacing doesn't get messed up.
var tabTextRows = ['','','','','',''];
$('td').click(function(){
var fret = $(this).index() - 1;
var line = $(this).parent().index() -1;
updateNote(fret, line);
});
function updateNote(fret, line){
var i;
for(i=0;i<tabTextRows.length;i++){
if(i == line) tabTextRows[i]+='-'+fret+'-';
else tabTextRows[i]+='---';
$('#tabText').val(tabTextRows.join('\n'));
}
}
I wrote the guitartabcreator website. Jacob Mattison is correct - I am using the text area for display purposes. Managing the data occurs in the backend. After seeing your site, it looks like you've got the basics of my idea down.

How to target text between two elements

Update Below
I'm trying to target the output of codemirror and add some custom events and styling to module elements.
Codemirror displays the following code as such.
<div><module type="content"></module><span>can contain other data</span></div>
In the DOM it is rendered between a series of spans.
<pre>
<span class="cm-tag"><div><module</span>
<span class="cm-attribute">type</span>
=
<span class="cm-string">"content"</span>
<span class="cm-tag">></module><span></span>
can contain other data
<span class="cm-tag"></span></div></span>
</pre>
The issue I'm having is trying to add a yellow background to the whole module element, but because the "=" part is between two elements, I'm not sure how to target it with a selector.
This is what I have right now, but because it does not include the text between the elements, there are gaps in the background color.
$('.cm-tag:contains("<module")').each(function () {
var $closingElement;
$(this).nextAll().each(function () {
if ($(this).text() == "></module>") {
$closingElement = $(this).next();
return false;
}
});
var $module =$(this).add($(this).nextUntil($closingElement));
$module.addClass('module');
});
Anyone have suggestion/ideas about how to accomplish this?
Update
I was able to get part way there by using the wrapAll jquery method, but the visible result still isn't quite right. Now the spaces and equal characters are removed from the wrapped element and placed after it.
<modulename"content"id"1234"/> = =
function hilightModules() {
$('.cm-tag:contains("<module")').each(function() {
var $module = $(this);
$(this).nextAll().each(function() {
$module = $module.add($(this));
// closing element
if ($(this).hasClass('cm-tag')) {
return false;
}
});
$module.wrapAll('<span class="module" />').click(function() {
// Do stuff
});
});
};
For adding click handlers to content text, your best bet is to just register a mousedown handler on the CodeMirror wrapper element, and, in that handler, determine whether the thing clicked is what you are looking for. Content elements may change at any time, and you don't want to register tons of handlers.
As for highlighting things, I'd recommend an overlay mode (see http://codemirror.net/demo/mustache.html for an example), rather than trying to do it with DOM munging (for the reasons listed above).
Like #Raminson said, you could target the <pre> tag to make the background span the entire section. Is this what you are looking for?
http://jsfiddle.net/ckaufman/CSzny/

Categories

Resources