How to drag and drop into text - javascript

Before trying to build something, I would like to determine if it is possible.
Start with a text area which can be pre-populated with text and which the user can add/delete text. Now, There are some small elements to the side. They can either be images or HTML elements such as a button or anchor links, whatever is easier. The user can drag an elements into the text area, and it will be inserted at the mouse cursor location and take up text space by pushing the existing text around it (the nearby element will also remain so the user can drop a second). The elements will remain as an element which can later be dragged elsewhere in the document or outside of the view port in which it will be removed. When the elements are positioned as desired, the location of the elements can be identified through some means (regex, dom, etc) so that they can be replaced with different content.
Line breaks will be needed. Ideally, it will work with jQuery and IE7+, however, the IE7 desire might need to be changed.
I’ve come across the following which are close but not quite.
http://skfox.com/jqExamples/insertAtCaret.html
http://jsbin.com/egefi (reference jQuery Drag & Drop into a Text Area)
http://jqueryui.com/droppable/#method-option
If you think it could be built and you have suggestions where I should start, please advise.

I did something very similar yesterday so why not sharing :)
My goal was to drop elements of text onto my textarea, in the middle of two lines of text while showing an indicator to where it would be dropped. I believe it will be useful to you ! ;)
$(document).ready(function() {
var lineHeight = parseInt($('#textarea').css('line-height').replace('px',''));
var previousLineNo = 0;
var content = $('#textarea').val();
var linesArray = content.length > 0 ? content.split('\n') : [];
var lineNo = 0;
var emptyLineAdded = false;
$('.draggable').draggable({
revert: function(is_valid_drop) {
if (!is_valid_drop) {
$('#textarea').val(content);
return true;
}
},
drag: function(event, ui) {
lineNo = getLineNo(ui, lineHeight);
if (linesArray.length > 0 && previousLineNo != lineNo) {
insertWhiteLine(lineNo, linesArray);
}
previousLineNo = lineNo;
}
});
$("#textarea").droppable({
accept: ".draggable",
drop: function( event, ui ) {
appendAtLine(lineNo, linesArray, ui.draggable.text());
$(ui.draggable).remove();
content = $('#textarea').val();
linesArray = content.split('\n');
if (linesArray[linesArray.length - 1] == '')
linesArray.pop(); //remove empty line
}
});
$('#textarea').on('input', function() {
if (!emptyLineAdded) {
console.log('input !');
console.log($('#textarea').val());
content = $('#textarea').val();
linesArray = content.split('\n');
if (linesArray[linesArray.length - 1] == '')
linesArray.pop(); //remove empty line
}
});
});
//Returns the top position of a draggable element,
//relative to the textarea. (0 means at the very top of the textarea)
function getYPosition(element, lineHeight) {
var participantIndex = $(element.helper.context).index();
var initPos = participantIndex * lineHeight;
var actualPos = initPos + element.position.top;
return actualPos;
}
//Returns the line number corresponding to where the element
//would be dropped
function getLineNo(element, lineHeight) {
return Math.round(getYPosition(element, lineHeight) / lineHeight);
}
//Inserts a white line at the given line number,
//to show where the element would be dropped in the textarea
function insertWhiteLine(lineNo, linesArray) {
$('#textarea').val('');
$(linesArray).each(function(index, value) {
if (index < lineNo)
$('#textarea').val($('#textarea').val() + value + '\n');
});
emptyLineAdded = true;
$('#textarea').val($('#textarea').val() + '_____________\n'); //white line
emptyLineAdded = false;
$(linesArray).each(function(index, value) {
if (index >= lineNo)
$('#textarea').val($('#textarea').val() + value + '\n');
});
}
//Inserts content of draggable at the given line number
function appendAtLine(lineNo, linesArray, content) {
$('#textarea').val('');
$(linesArray).each(function(index, value) {
if (index < lineNo)
$('#textarea').val($('#textarea').val() + value + '\n');
});
$('#textarea').val($('#textarea').val() + content + '\n'); //content to be added
$(linesArray).each(function(index, value) {
if (index >= lineNo)
$('#textarea').val($('#textarea').val() + value + '\n');
});
}

Related

move fake cursor to position taken from clicked character

I have a div with text using monospace font, and I need to display a cursor in the place where I click, I have functions that display text with cursor:
function draw() {
var text = textarea.val();
var html;
if (pos == text.length) {
html = encode(text) + '<span class="cursor"> </span>';
} else {
html = encode(text.slice(0, pos)) + '<span class="cursor">' +
encode(text[pos+1]) + '</span>' + encode(text.slice(pos+1));
}
output.html(html);
}
and function that get cursor position based on x/y coordinate of the mouse event:
function get_char_pos(div, text, event) {
var num_chars = get_num_chars(div);
var cursor = div.find('.cursor');
var rect = cursor[0].getBoundingClientRect();
var width = rect.width;
var height = rect.height;
var offset = div.offset();
var col = Math.floor((event.pageX-offset.left)/width);
var row = Math.floor((event.pageY-offset.top)/height);
var try_pos = col + (row > 0 ? num_chars * row : 0);
return try_pos;
}
It almost working except when text contain tabs (tabs are replaced by 4 spaces by encode function). I've try to fix tabs using this:
var before = text.slice(0, try_pos);
var tabs = before.match(/\t/g);
var fix = tabs ? tabs * 3 : 0;
try_pos += fix;
return try_pos > text.length ? text.lenght : try_pos;
but this don't work. It should also work for a case when I click on space that may be part of tab. How to fix it when text contain tabs?
Here is codepen demo
The tab character is the issue. It's a single character which means the string it's not calculated as four characters in the text.slice. If you replace \t with four spaces your issue is solved.

Set text-cursor position in a textarea

I'm working on a BBCode editor and here is the code:
var txtarea = document.getElementById("editor_area");
function boldText() {
var start = txtarea.selectionStart;
var end = txtarea.selectionEnd;
var sel = txtarea.value.substring(start, end);
var finText = txtarea.value.substring(0, start) + '[b]' + sel + '[/b]' + txtarea.value.substring(end);
txtarea.value = finText;
txtarea.focus();
}
Everything is OK except one thing which is the position of the text-cursor. When I click on the boldText button, it sets the cursor position at the end of the Textarea!!
Actually, I want to be able to set the cursor position at a certain index. I want something like this:
txtarea.setFocusAt(20);
After refocusing the textarea with txtarea.focus(), add this line:
txtarea.selectionEnd= end + 7;
That will set the cursor seven positions ahead of where it was previously, which will take [b][/b] into account.
Example
document.getElementById('bold').addEventListener('click', boldText);
function boldText() {
var txtarea = document.getElementById("editor_area");
var start = txtarea.selectionStart;
var end = txtarea.selectionEnd;
var sel = txtarea.value.substring(start, end);
var finText = txtarea.value.substring(0, start) + '[b]' + sel + '[/b]' + txtarea.value.substring(end);
txtarea.value = finText;
txtarea.focus();
txtarea.selectionEnd= end + 7;
}
#editor_area {
width: 100%;
height: 10em;
}
<button id="bold">B</button>
<textarea id="editor_area"></textarea>
if you are using jquery you can do it like this.
$('textarea').prop('selectionEnd', 13);
you can use these 2 functions below written by Jamie Munro (setSelectionRange() & setCaretToPos()):
function setSelectionRange(input, selectionStart, selectionEnd) {
if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(selectionStart, selectionEnd);
}
else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
}
}
function setCaretToPos (input, pos) {
setSelectionRange(input, pos, pos);
}
EXAMPLE:
for example, if you want to set the caret at the end of your textarea you can have this:
setCaretToPos(document.getElementById('textarea'), -1);
Through JQuery:
var cursorPos = $('#textarea').prop('selectionStart');
$('#textarea').prop('selectionEnd',cursorPos-2);
Realizing this is an older question, this is offered only as something to think about as an option now because it may likely be more efficient than extracting and assembling pieces of the textarea value string, and it sets the cursor automatically based on the fourth argument of setRangeText and autofocuses also. It works in Firefox 66.0.02 and I haven't tested it elsewhere. The cursor is placed after the '[/b]'.
t = document.getElementById("editor_area");
b = t.selectionStart,
e = t.selectionEnd + 3; // length of '[b]'
t.setSelectionRange( b, b );
t.setRangeText( '[b]' );
t.setSelectionRange( e, e );
t.setRangeText( '[/b]', e, e, 'end' );
This is a little OT, but if anyone is interested:
Brief: Set cursor inside input element throug row and column
Dependency: setSelectionRange() from #ashkan nasirzadeh
Example call: setTextCursor(textarea,textarea.val, 0, 1);
// #brief: set cursor inside _input_ at position (column,row)
// #input: input DOM element. E.g. a textarea
// #content: textual content inside the DOM element
// #param row: starts a 0
// #param column: starts at 0
function setTextCursor(input, content, row, column){
// search row times:
var pos = 0;
var prevPos = 0;
for( var i = 0; (i<row) && (pos != -1); ++i){
prevPos = pos;
pos = content.indexOf("\n",pos+1);
}
// if we can't go as much down as we want,
// go as far as worked
if(-1 == pos){ pos = prevPos; }
if(0 != row)
++pos; // one for the linebreak
// prevent cursor from going beyond the current line
var lineEndPos = content.indexOf("\n", pos+1);
if((-1 != lineEndPos) &&
(column > lineEndPos-pos)){
// go *only* to the end of the current line
pos = lineEndPos;
} else{
// act as usual
pos += column
}
setSelectionRange(input, pos,pos);
}

How to set cursor position with Jquery using focus?

I'm having trouble with my function. I made a text editor with BBcode.
Its working very well but the cursor always get back to the end of the textarea.
Here is how it works;
var element = document.getElementById('textEdit');
var lastFocus;
$(document.body).on('click','.editBout', function(e) {
e.preventDefault();
e.stopPropagation();
var style = ($(this).attr("data-style"));
// Depending on the button I set the BBcode
switch (style) {
case 'bold':
avS = "[b]";
apS = "[/b]";
break;
}
if (lastFocus) {
setTimeout(function () { lastFocus.focus() }, 10);
var textEdit = document.getElementById('textEdit');
var befSel = textEdit.value.substr(0, textEdit.selectionStart);
var aftSel = textEdit.value.substr(textEdit.selectionEnd, textEdit.length);
var select = textEdit.value.substring(textEdit.selectionStart, textEdit.selectionEnd);
textEdit.value = befSel + avS + select + apS + aftSel;
textEdit = textEdit.value
textEdit = BBcoder(textEdit);
document.getElementById('editorPreview').innerHTML = textEdit;
}
return (false);
});
This last part here triggers the preview event
$(document.body).on('blur', '#textEdit', function() {
lastFocus = this;
});
So i want it to come back to last focus but at a given position computed out of my selection + added bbcode length.

TinyMCE. after adding span cannot continue typing out of it

I am trying to create a plugin for TinyMCE, so user can add floating tips for selected area.
All i need is to put selected content into span, i do it this way:
var formated =
'<span id="tooltip_widget_' + id + '">'
+ selectedtext
+ '</span>;
ed.selection.setContent(formated);
And it works well in Firefox, i can add text to span and continue typing out of it.
But in Chrome and IE all the following text goes into the added span. And the only way to continue typing out of it - via html editor.
I tried include additional caret placeholder span after the insertion and collapse after it and then delete this placeholder to make sure the caret will be after the inserted span.
But it doesn't help. In chrome and IE if caret is at the end of span, it continues typing inside this span.
Please advice how to solve this.
Solution can be found in this fiddle or as code here:
<script type="text/javascript">
function plugin_work(){
var ed = tinymce.editors[0];
var innerSpanId = 0;
var node = ed.selection.getNode();
// Get the selected contents as text and place it in the input
if (ed.selection.getNode().className == "tooltipedurl") {
var innerSpanId = node.id;
if (innerSpanId != 0) {
var innerSpanHTML = ed.dom.get('data_' + innerSpanId).innerHTML;
}
} else {
var innerSpanHTML = ed.selection.getContent({format : 'html'});
}
var id = new Date().getTime();
var node = ed.selection.getNode();
if (node.className == "tooltipedurl") {
var innerSpanId = node.id;
if (innerSpanHTML != 0) {
ed.dom.get('data_' + innerSpanId).innerHTML = innerSpanHTML;
} else {
ed.dom.remove(node);
ed.selection.setContent(node.innerHTML);
ed.dom.remove(ed.dom.get('data_' + innerSpanId));
ed.focus();
}
} else {
var formated =
'<span id=\"tooltip_widget_' + id + '\" class=\"tooltipedurl\" name="tip">'
+ innerSpanHTML
+ '</span><span id="caret_placeholder_' + id + '" name="caret_placeholder">\u200b</span>';
ed.selection.setContent(formated);
var rng = tinymce.DOM.createRng(); // the range obj
var $caret_placeholder = $(ed.getBody()).find ('#caret_placeholder_'+id); // find the correct selector so that caret_placeholder is the element of your editor text
// rng.setStart(caret_placeholder.firstChild, f.textFragment.value.length); // 0 is the offset : here it will be at the beginning of the line.
// rng.setEnd(caret_placeholder.firstChild, f.textFragment.value.length);
//console.log(caret_placeholder);
rng.setStartAfter($caret_placeholder.get(0));
rng.setEndAfter($caret_placeholder.get(0));
ed.selection.setRng(rng);
//ed.selection.select(caret_placeholder);
//$(caret_placeholder).html('');
ed.focus();
tinyMCE.activeEditor.dom.add(tinyMCE.activeEditor.getBody(), 'span', {id : 'data_tooltip_widget_' + id, style : 'display:none'}, innerSpanHTML);
ed.onKeyUp.add(function(ed, e) {
if ($caret_placeholder = $(ed.getBody()).find ('#caret_placeholder_'+id)) {
var content = $caret_placeholder.get(0).innerHTML;
ed.dom.remove($caret_placeholder.get(0));
ed.selection.setContent(content);
}
});
}
}
tinymce.create('tinymce.plugins.floatingtipsPlugin', {
init : function(ed, url) {
// Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('mcefloatingtips');
ed.addCommand('mcefloatingtips', function() {
var se = ed.selection;
// No selection and not in span
if (se.isCollapsed() && se.getNode().className != "tooltipedurl") {
return;
}
ed.windowManager.open({
file : url + '/dialog.htm',
width : 320 + parseInt(ed.getLang('floatingtips.delta_width', 0)),
height : 120 + parseInt(ed.getLang('floatingtips.delta_height', 0)),
inline : 1
}, {
plugin_url : url, // Plugin absolute URL
some_custom_arg : 'custom arg' // Custom argument
});
});
// Register floatingtips button
ed.addButton('floatingtips', {
title : 'Add/Edit floating tip',
cmd : 'mcefloatingtips',
image : url + '/img/floating_tips.gif'
});
// Add a node change handler
ed.onNodeChange.add(function(ed, cm, n) {
var se = ed.selection;
cm.setActive('floatingtips', se.getNode().className == "tooltipedurl");
cm.setDisabled('floatingtips', se.isCollapsed() && se.getNode().className != "tooltipedurl");
});
ed.contentCSS.push(url + '/css/floatingtips.css');
},
createControl : function(n, cm) {
return null;
},
getInfo : function() {
return {
longname : 'floatingtips plugin',
author : 'Some author',
authorurl : 'http://tinymce.moxiecode.com',
infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/floatingtips',
version : "1.0"
};
}
});
tinymce.PluginManager.add('floatingtips', tinymce.plugins.floatingtipsPlugin);
/**
*
* Here goes dialog.js
* What exactly my plugin does
*
* ================== GOAL =====================
* Goal - to wrap selected text with span like this:
* <span class="tooltipedurl", id="tooltip_widget_" + {someuniueID}> SELECTED TEXT </span>
* Add to the end of the editor hidden element with tooltip text like this:
* <span id="data_tooltip_widget_ + {someuniueID} style="display:none"> TOOLTIP TEXT </span>
*
*/
/**
* ================= ALGORITHM ==================
* If some text selected, or if we have caret inside span with class tooltipedurl.
* We got plugin buton - active.
* On click we see popup form with two fields.
* first with selected text, (it is hidden, user shouldn't be able to modify it from popup form)
* second is the tip input(textarea filed) we load here old tip if the caret inside the span with tip.
*
* if text selected:
* we got it from the popup form {f.textFragment.value} and replace it with
* <span id=\"tooltip_widget_' + id + '\" class=\"tooltipedurl\" name="tip">'+ f.textFragment.value + '</span>
* also we create hidden span in the end of editor with tip value from the form {f.newTip.value}
* tinyMCE.activeEditor.dom.add(tinyMCE.activeEditor.getBody(), 'span', {id : 'data_tooltip_widget_' + id, style : 'display:none'}, f.newTip.value);
*
* if caret inside the span which already has tooltip
* we have in popup form current tooltip message and can edit it and put new value to the corresponding hidden span
* ed.dom.get('data_' + innerSpanId).innerHTML = f.newTip.value;
*
* if the new tip value = 0, we delete span which contains the text and delete correspondig
* hiden element with tooltip text
*
* more detailed comments i added to the script below
*/
var ExampleDialog = {
init : function() {
var ed = tinyMCEPopup.editor;
// f is a form from PopUp
var f = document.forms[0];
// if selection inside the span with class tooltipedurl we will put here the id of this span
var innerSpanId = 0;
var node = ed.selection.getNode();
// Get the selected contents as text and place it in the input fields if we are inside the span with class tooltipedurl
if (ed.selection.getNode().className == "tooltipedurl") {
var innerSpanId = node.id;
//taking all the text to the input from the span even if only part of it was selected
f.textFragment.value = node.innerText;
if (innerSpanId != 0) {
//taking current tooltip text from the corresponding hidden span
f.newTip.value = ed.dom.get('data_' + innerSpanId).innerHTML;
}
} else {
//if selected text is not in the span with class tooltipedurl we just get as html to apply tooltip later
f.textFragment.value = ed.selection.getContent({format : 'html'});
}
},
insert : function() {
var ed = tinyMCEPopup.editor;
var f = document.forms[0];
var id = new Date().getTime();
var node = ed.selection.getNode();
//if selection is inside the span#tooltipedurl - we gonna edit tooltip text
if (node.className == "tooltipedurl") {
var innerSpanId = node.id;
if (f.newTip.value != 0) {
//If new tooltip is not 0, we replace inner html of correspondig span in the end of editor
ed.dom.get('data_' + innerSpanId).innerHTML = f.newTip.value;
} else {
//If new tooltip value is 0 - we delete correspondig span in the end of editor and remove <span> tags from text
ed.dom.remove(node);
ed.selection.setContent(node.innerHTML);
ed.dom.remove(ed.dom.get('data_' + innerSpanId));
}
} else {
//if selection doesn't have tooltip, we place it in the tags with unique id and class tooltipedurl
var formated =
'<span id=\"tooltip_widget_' + id + '\" class=\"tooltipedurl\" name="tip">'
+ f.textFragment.value
+ '</span>';
ed.selection.setContent(formated);
/**
* THE PROBLEM IS
* when we add this span and user trying to continue typing.
* in Chrome and IE all the following text goes in this new span.
* In firefox it works OK.
*
*/
//Here i am trying to put caret right after added span with dom.range
var rng = tinymce.DOM.createRng(); // the range obj
var caret_placeholder = ed.dom.get('tooltip_widget_' + id);
// rng.setStart(caret_placeholder.firstChild, f.textFragment.value.length);
// rng.setEnd(caret_placeholder.firstChild, f.textFragment.value.length);
rng.setStartAfter(caret_placeholder);
rng.setEndAfter(caret_placeholder);
ed.selection.setRng(rng);
//But it doesn't help...
//creating invisible element with tooltip message in the end of the editor
tinyMCE.activeEditor.dom.add(tinyMCE.activeEditor.getBody(), 'span', {id : 'data_tooltip_widget_' + id, style : 'display:none'}, f.newTip.value);
}
tinyMCEPopup.close();
}
};
/**
* I don't know how to include popup window from my plugin here
* But ih has 2 fields
* f.textFragment.value ==> it is the selected text (this field is hidden)
* f.newTip.value ==> text input with the tip.
*
* so when user selects some text and clicks add floating tip button. he sees the form with 1 text field and can add new tooltip or edit old one
*
*/
//tinyMCEPopup.onInit.add(ExampleDialog.init, ExampleDialog);
// Initialize TinyMCE with the new plugin and listbox
tinyMCE.init({
plugins : '-example, floatingtips', // - tells TinyMCE to skip the loading of the plugin
mode : "textareas",
theme : "advanced",
theme_advanced_buttons1 : "code,mylistbox,mysplitbutton,bold,italic,underline,separator,strikethrough,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,undo,redo,link,unlink, floatingtips",
theme_advanced_buttons2 : "",
theme_advanced_buttons3 : "",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom"
});
</script>
<form method="post" action="dump.php">
<textarea name="content">
test
</textarea>
</form>
<div onclick="plugin_work();" style="cursor:pointer;background-color:green;width:70px;">Button</div>

Finding number of lines in an html textarea

I'm writing a mobile web application where scrollbars are not displayed on the device's browser. Due to this, I'm trying to dynamically modify the height of the textarea to make it bigger, however I don't know of any way to actually get the line count on an html textarea. Any help would be greatly appreciated!
EDIT
So I realize now that it's not newlines per se, but actual line wrapping. So when one line finishes it wraps the text to the next line. It appears as if it is a new line. Any way to count the number of these? Thanks!
The number of lines in the textarea would be
textarea.value.match(/\n/g).length + 1
I have created a plugin to handle line counting and wrap detection in a <textarea>.
I hope someone can use it.
Code on BitBucket
Sample Usage
var result = $.countLines("#textarea");
result.actual // The number of lines in the textarea.
result.wraps // The number of lines in the textarea that wrap at least once.
result.wrapped // The total number of times all lines wrap.
result.blank // The number of blank lines.
result.visual // The approximate number of lines that the user actually sees in the textarea
Working Demonstration
/*! Textarea Line Count - v1.4.1 - 2012-12-06
* https://bitbucket.org/MostThingsWeb/textarea-line-count
* Copyright (c) 2012 MostThingsWeb (Chris Laplante); Licensed MIT */
(function($) {
$.countLines = function(ta, options) {
var defaults = {
recalculateCharWidth: true,
charsMode: "random",
fontAttrs: ["font-family", "font-size", "text-decoration", "font-style", "font-weight"]
};
options = $.extend({}, defaults, options);
var masterCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
var counter;
if (!ta.jquery) {
ta = $(ta);
}
var value = ta.val();
switch (options.charsMode) {
case "random":
// Build a random collection of characters
options.chars = "";
masterCharacters += ".,?!-+;:'\"";
for (counter = 1; counter <= 12; counter++) {
options.chars += masterCharacters[(Math.floor(Math.random() * masterCharacters.length))];
}
break;
case "alpha":
options.chars = masterCharacters;
break;
case "alpha_extended":
options.chars = masterCharacters + ".,?!-+;:'\"";
break;
case "from_ta":
// Build a random collection of characters from the textarea
if (value.length < 15) {
options.chars = masterCharacters;
} else {
for (counter = 1; counter <= 15; counter++) {
options.chars += value[(Math.floor(Math.random() * value.length))];
}
}
break;
case "custom":
// Already defined in options.chars
break;
}
// Decode chars
if (!$.isArray(options.chars)) {
options.chars = options.chars.split("");
}
// Generate a span after the textarea with a random ID
var id = "";
for (counter = 1; counter <= 10; counter++) {
id += (Math.floor(Math.random() * 10) + 1);
}
ta.after("<span id='s" + id + "'></span>");
var span = $("#s" + id);
// Hide the span
span.hide();
// Apply the font properties of the textarea to the span class
$.each(options.fontAttrs, function(i, v) {
span.css(v, ta.css(v));
});
// Get the number of lines
var lines = value.split("\n");
var linesLen = lines.length;
var averageWidth;
// Check if the textarea has a cached version of the average character width
if (options.recalculateCharWidth || ta.data("average_char") == null) {
// Get a pretty good estimation of the width of a character in the textarea. To get a better average, add more characters and symbols to this list
var chars = options.chars;
var charLen = chars.length;
var totalWidth = 0;
$.each(chars, function(i, v) {
span.text(v);
totalWidth += span.width();
});
// Store average width on textarea
ta.data("average_char", Math.ceil(totalWidth / charLen));
}
averageWidth = ta.data("average_char");
// We are done with the span, so kill it
span.remove();
// Determine missing width (from padding, margins, borders, etc); this is what we will add to each line width
var missingWidth = (ta.outerWidth() - ta.width()) * 2;
// Calculate the number of lines that occupy more than one line
var lineWidth;
var wrappingLines = 0;
var wrappingCount = 0;
var blankLines = 0;
$.each(lines, function(i, v) {
// Calculate width of line
lineWidth = ((v.length + 1) * averageWidth) + missingWidth;
// Check if the line is wrapped
if (lineWidth >= ta.outerWidth()) {
// Calculate number of times the line wraps
var wrapCount = Math.floor(lineWidth / ta.outerWidth());
wrappingCount += wrapCount;
wrappingLines++;
}
if ($.trim(v) === "") {
blankLines++;
}
});
var ret = {};
ret["actual"] = linesLen;
ret["wrapped"] = wrappingLines;
ret["wraps"] = wrappingCount;
ret["visual"] = linesLen + wrappingCount;
ret["blank"] = blankLines;
return ret;
};
}(jQuery));
result = jQuery.countLines("#textarea");
jQuery('#display').html(
'<span>Actual: ' + result.actual + '</span>' +
'<span>Blank: ' + result.blank + '</span>' +
'<span>Visual: ' + result.visual + '</span>' +
'<span>Wrapped: ' + result.wrapped + '</span>' +
'<span>Wraps: ' + result.wraps + '</span>'
);
#textarea {
width: 150px;
height: 80px;
}
#display span {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="textarea">text
here
this is a longer line so that it will wrap in the box longer longer longer</textarea>
<div id="display"></div>
This is an efficient and accurate method to count the number of lines in a text area, including wrapped lines.
/** #type {HTMLTextAreaElement} */
var _buffer;
/**
* Returns the number of lines in a textarea, including wrapped lines.
*
* __NOTE__:
* [textarea] should have an integer line height to avoid rounding errors.
*/
function countLines(textarea) {
if (_buffer == null) {
_buffer = document.createElement('textarea');
_buffer.style.border = 'none';
_buffer.style.height = '0';
_buffer.style.overflow = 'hidden';
_buffer.style.padding = '0';
_buffer.style.position = 'absolute';
_buffer.style.left = '0';
_buffer.style.top = '0';
_buffer.style.zIndex = '-1';
document.body.appendChild(_buffer);
}
var cs = window.getComputedStyle(textarea);
var pl = parseInt(cs.paddingLeft);
var pr = parseInt(cs.paddingRight);
var lh = parseInt(cs.lineHeight);
// [cs.lineHeight] may return 'normal', which means line height = font size.
if (isNaN(lh)) lh = parseInt(cs.fontSize);
// Copy content width.
_buffer.style.width = (textarea.clientWidth - pl - pr) + 'px';
// Copy text properties.
_buffer.style.font = cs.font;
_buffer.style.letterSpacing = cs.letterSpacing;
_buffer.style.whiteSpace = cs.whiteSpace;
_buffer.style.wordBreak = cs.wordBreak;
_buffer.style.wordSpacing = cs.wordSpacing;
_buffer.style.wordWrap = cs.wordWrap;
// Copy value.
_buffer.value = textarea.value;
var result = Math.floor(_buffer.scrollHeight / lh);
if (result == 0) result = 1;
return result;
}
Demo here
I haven't tried using the function discussed in this blog, but you may find it useful.
http://kirblog.idetalk.com/2010/03/calculating-cursor-position-in-textarea.html
Basically, if you create a div and then copy the text into that div, with the same width and font characteristics, you can then get the information you need, such as the number of lines. The number of lines in this example would be easy, in that if you know how many pixels high a single line would be, then just find the width of the test div and you can get a pretty accurate idea as to how many lines are in your textarea.
Get scrollHeight, subtract top+bottom padding, divide by lineHeight.
I'm pretty sure there is no reasonable way to count the number of lines as displayed in the browser especially considering some browsers (Safari) allow the user to resize textareas.
It'd be hacky, but your best bet might be to just estimate based on the total characters divided by average number of characters per line. :-/
Maybe there is a way to get the "raw" number of "visual" lines. You should read the scrollHeight property of the textarea and divide it by the height of a line. Let's try.
Start with this HTML:
<textarea id="ta" cols="50" rows="10"></textarea>
Then:
var line_height = Math.floor($("#ta").height() / parseInt($("#ta").attr("rows")));
var dirty_number_of_lines = Math.ceil($("#ta")[0].scrollHeight / line_height);
I am not sure if that really works, just a mad theory.
You can calculate is as so:
var length = $('#textarea').val().split("\n").length;
The number of characters allowed per line is dictated by the "cols" attribute of the textarea.
<textarea rows="10" cols="80"></textarea>
Assuming 80 characters per line, a good estimate may be:
var approxNumLines = textareaElement.value.length / textareaElement.cols ;
Doesn't account for word-break and word-wrap.

Categories

Resources