Set different font-size into textarea - javascript

Is it possible to diversify the font size only in some parts of the text in a textarea with Javascript?
custom_button.onclick = function () {
// IE version
if (document.selection != undefined)
{
component_name.focus();
var sel_ie = document.selection.createRange();
textNew = sel_ie.text;
}
// Mozilla version
else
{
var startPos = document.getElementById(component_name).selectionStart;
var endPos = document.getElementById(component_name).selectionEnd;
textNew = document.getElementById(component_name).value.substring(startPos, endPos);
}
var finalText = text.substr(0,startPos) + '<font size="100">' + textNew + '</font>' + text.substr(endPos);
}
When I usually write the code above I achieve the following result into the textarea:
This <font size="100">is the</font> text

Related

Get Text from Xpath and Highlight it

I am trying to build a E pub Reader. I am able to highlight the user selected text and i am getting the x path of that particular selected text. After that i am trying to build a function which takes x path as parameter and show the user selected text by changing background color. but its not working.
Code:-
function uiWebview_restoreSelection() {
var selectionDetails = "/HTML[1]/BODY[1]/DIV[1]/text()[1]|910|/HTML[1]/BODY[1]/DIV[1]/text()[1]|930";
//alert("selectionDetails"+selectionDetails);
if (selectionDetails != null) {
selectionDetails = selectionDetails.split(/\|/g);
alert("selectionDetails" + selectionDetails);
if (typeof window.getSelection != 'undefined') {
var selection = window.getSelection();
selection.removeAllRanges();
var range = document.createRange();
var selectionDetails0 = selectionDetails[0];
alert("selectionDetails0" + selectionDetails0);
selectionDetails0 = selectionDetails0.replace(/\//g, "/h:");
selectionDetails0 = selectionDetails0.replace("h:t", "t");
alert("selectionDetails0" + selectionDetails0);
var selectionDetails2 = selectionDetails[2];
alert("selectionDetails2" + selectionDetails2);
selectionDetails2 = selectionDetails2.replace(/\//g, "/h:");
selectionDetails2 = selectionDetails2.replace("h:t", "t");
alert("selectionDetails2" + selectionDetails2);
range.setStart(document.evaluate(selectionDetails0, document, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue, Number(selectionDetails[1]));
range.setEnd(document.evaluate(selectionDetails2, document, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue, Number(selectionDetails[3]));
document.designMode = "on";
var newSpanMark = document.createElement("span");
document.execCommand("HiliteColor", false, "red");
range.insertNode(newSpanMark);
document.designMode = "off";
}
}
}
Please suggest for the above problem.
Thanks in Advance

How to transpose two characters in a textarea

How can I get at the content of a text area and swap the two characters around the cursor, in Javascript? I want to write a tiny, but useful Chrome extension that will let me do this when I mistype in gmail. (I'm assuming that the the main editing area in gmail is a textarea).
This may be a question too stupid to ask here. In any case, I have searched for an answer and failed. I'm not a real programmer, but I have written snippets to do this in other scripting languages. It's easy enough to do it Firefox, for example, with an autohotkey script. For some reason the Javascript quite defeats me.
See the code in http://jsfiddle.net/Lg3Ng/
HTML:
<textarea id="my_text" onclick="changeChar();"></textarea>
JAVASCRIPT:
function changeChar() {
var pos = getCaretPosition(document.getElementById("my_text"));
//alert(pos);
if (pos > 0) swapChars(pos - 1);
}
function swapChars(pos) {
var cur_val = document.getElementById("my_text").value;
var firstChar = cur_val.charAt(pos);
var secondChar = cur_val.charAt(pos + 1);
var startString = cur_val.substr(0, pos);
var endString = cur_val.substring(pos + 2);
document.getElementById("my_text").value = startString + secondChar + firstChar + endString;
}
// From http://demo.vishalon.net/getset.htm
function getCaretPosition(ctrl) {
var CaretPos = 0;
// IE Support
if (document.selection) {
ctrl.focus();
var Sel = document.selection.createRange();
Sel.moveStart('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (ctrl.selectionStart || ctrl.selectionStart == '0'){
CaretPos = ctrl.selectionStart;
}
return (CaretPos);
}

Suggestion to improve the script

In the below script I am trying to highlight all the words in a sentence
function SearchQueue(text)
{
if(text !== null)
{
text = text.replace(/“/g, "\"");
text = text.replace(/”/g, "\"");
text = text.replace(/’/g, "\'");
text = text.replace(/‘/g, "\'");
text = text.replace(/–/g, "\-");
text = text.replace(/ +(?= )/g,'');
$.trim(text);
text = text.replace(/\d\.\s+|[a-z]\)\s+|•\s+|[A-Z]\.\s+|[IVX]+\.\s+/g, "");
text = text.replace(/([0-9A-Z]+[.)]|•)\s+/gi, "");
text = text.replace(/(\r\n|\n|\r)/gm," ");
}
var words = text.split(' ');
for(var i=0;i<words.length;i++)
$('*').highlight(''+words[i]+''); // Will highlight the script with background color
}
But this is making my page "unresponsive". Please suggest me to improve the script...
You are selecting the entire dom tree in each iteration which may explain the unresponsiveness.
Try the following:
var body = $('body'); // since thats where all the text should live
for(var i=0;i<words.length;i++){
body.highlight(''+words[i]+''); // Will highlight the script with background color
}
Here's my first set of adjustments:
var $all = $('*');
function SearchQueue(text) {
if(text) {
text = text.replace(/[“”]/g, '"');
text = text.replace(/[’‘]/g, "'");
text = text.replace(/–/g, '-');
text = text.replace(/\s+/g, ' ');
$.trim(text);
text = text.replace(/\d\.\s+|[a-z]\)\s+|•\s+|[A-Z]\.\s+|[IVX]+\.\s+/g, '');
text = text.replace(/([0-9A-Za-z]+[.)]|•)\s+/g, '');
var words = text.split(' ');
for(var i = 0; i < words.length; i++) {
$all.highlight(words[i]); // Will highlight the script with background color
}
}
}
You can combine a few of your replaces using a match evaluator (don't know what javascript calls them).
example : http://jsfiddle.net/zyqVE/
function match_eval(m){
switch (m){
case "“":case "”":
return "\"";
case "‘":case "’":
return "'";
// etc...
}
return m;
}
alert("this “i“ a test".replace(/[““’‘–]/g, match_eval));
in context :
function match_eval(m){
switch (m){
case "“":case "”":
return "\"";
case "‘":case "’":
return "'";
case "–"
return "-";
}
return m;
}
function SearchQueue(text)
{
if(text !== null)
{
text = text.replace(/[“”’‘–]/g, match_eval);
text = text.replace(/ +(?= )/g,'');
$.trim(text);
text = text.replace(/\d\.\s+|[a-z]\)\s+|•\s+|[A-Z]\.\s+|[IVX]+\.\s+/g, "");
text = text.replace(/([0-9A-Z]+[.)]|•)\s+/gi, "");
text = text.replace(/(\r\n|\n|\r)/gm," ");
}
var words = text.split(' ');
for(var i=0;i<words.length;i++)
$('*').highlight(''+words[i]+''); // Will highlight the script with background color
}

Find carret position x y inside textarea with javascript

What Im trying to do is - i dont know the name maybe - a Prediction Help Inputter inside a textarea. It uses jquery autocomplete. When the user types '[[g ' inside textarea (id=test), a input with autocomplete is opened (id=example), so it search in 'data'. When the user find the desired data, he must press Shif+Enter to insert the data into the textarea, closing with ']]'.
How could I find the position of the carret to make the input appears near there?
I dont want to find the index of the carret, but something like the x y absolute position.
What do you suggest me?
Code above:
<textarea onkeydown="predicao(this);" cols="40" rows="10" id="test" onfocus="this.focus()"></textarea>
<input id="example" style="display: none;" onkeyup="insert(this, event);"/>
<script language="Javascript">
<!--
function predicao(objeto){
comprimento = objeto.value.length;
var antipenultimo = comprimento - 4;
var input = objeto.value.substring(antipenultimo,comprimento);
var output = "";
for(i=0; i<input.length; ++i){
if(output != "") output += ", ";
output += input.charCodeAt(i);
}
if (output == "91, 91, 103, 32"){
var preditor = document.getElementById('example');
preditor.value = '';
preditor.style.display = 'block';
preditor.focus();
preditor.select();
}
}
function insert(objeto, evt){
var e = evt || event;
var code = e.keyCode || e.which;
if(e.shiftKey && code == '13') {
var texto = document.getElementById('test').value;
texto += objeto.value+']]';
document.getElementById('test').focus();
document.getElementById('test').value = texto;
objeto.style.display = 'none';
}
}
$(document).ready(function(){
var data = "Afrikaans Català Deutsch English Esperanto Suomi Français Galego Hrvatski Magyar Bahasa Indonesia Italiano Basa Jawa".split(" ");
$("#example").autocomplete(data);});
</script>
Something like:
var pos = $('textarea').caret(); // using caret plugin...
var lines = $('textarea').val().slice(0, pos).replace(/\t/g, ' ').split('\n');
var y = lines.length;
var x = lines[y-1].length;
Should work reasonably well for fix-width fonts.
If you're looking to do it via JS only:
function doGetCaretPosition (ctrl) {
var CaretPos = 0; // IE Support
if (document.selection) {
ctrl.focus ();
var Sel = document.selection.createRange ();
Sel.moveStart ('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (ctrl.selectionStart || ctrl.selectionStart == '0')
CaretPos = ctrl.selectionStart;
return (CaretPos);
}
Courtesy: http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/
Demo: http://demo.vishalon.net/getset.htm

Rewrite a IE Code to a FF Code

This is the code (now is full):
HTML:
<div id="content" contentEditable="true" onkeyup="highlight(this)">This is some area to type.</div>
Javascript:
function highlight(elem){
// store cursor position
var cursorPos=document.selection.createRange().duplicate();
var clickx = cursorPos.getBoundingClientRect().left;
var clicky = cursorPos.getBoundingClientRect().top;
// copy contents of div
var content = elem.innerHTML;
var replaceStart = '';
var replaceEnd = '';
// only replace/move cursor if any matches
// note the spacebands - this prevents duplicates
if(content.match(/ test /)) {
elem.innerHTML = content.replace(/ test /g,' '+replaceStart+'test'+replaceEnd+' ');
// reset cursor and focus
cursorPos = document.body.createTextRange();
cursorPos.moveToPoint(clickx, clicky);
cursorPos.select();
}
}
Just woks on IE, unhapply.
Anyone can 'adjust' this code, to work on FF too!...
Thanks
Edit[1]:
Div Editable and More... More
This code replaces a especific word by the same word formatted...
And the caret (cursor) stay always after the word replaced! <<< "This is the big"
But just works on IE, and I like so much to rewrite this code to work on FF... but I can't do it... Its so hard...
Anyone can help?
Edit[2]:
My problem is just with this part:
// reset cursor and focus
cursorPos = document.body.createTextRange();
cursorPos.moveToPoint(clickx, clicky);
cursorPos.select();
Because, moveToPotion and select functions just works on IE... Until then it is easy...
On FF there is another set of functions that make it possible... But i don't know how to write another code that do the same things. Do you got it?
You can preserve the caret position by inserting a marker element at its current location before doing your replacement on the element's innerHTML. (Using DOM methods to traverse the text nodes and searching each for the text you want would be preferable to using innerHTML, by the way).
The following works, so long as the caret is not positioned within or adjacent to the word "text". I also added a timer to prevent calling this function every time a key is pressed and to wait for the user to stop typing for half a second.
function insertCaretMarker() {
var range;
var markerId = "sel_" + new Date() + "_" + ("" + Math.random()).substr(2);
if (window.getSelection) {
var sel = window.getSelection();
range = sel.getRangeAt(0);
range.collapse(true);
var markerEl = document.createElement("span");
markerEl.appendChild(document.createTextNode("\u00a0"));
markerEl.id = markerId;
range.insertNode(markerEl);
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
range.collapse(true);
if (range.pasteHTML) {
range.pasteHTML("<span id=\"" + markerId + "\"> </span>");
}
}
return markerId;
}
function restoreCaret(markerId) {
var el = document.getElementById(markerId);
var range;
if (el) {
if (window.getSelection && document.createRange) {
var sel = window.getSelection();
range = document.createRange();
range.setStartBefore(el);
sel.removeAllRanges();
sel.addRange(range);
} else if (document.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(el);
range.collapse(true);
range.select();
}
el.parentNode.removeChild(el);
}
}
function preserveCaretPosition(func) {
var id = insertCaretMarker();
func();
restoreCaret(id);
}
var highlightTimer;
function highlight(elem) {
if (highlightTimer) {
window.clearTimeout(highlightTimer);
}
highlightTimer = window.setTimeout(function() {
highlightTimer = null;
var replaceStart = '<b>';
var replaceEnd = '</b>';
// only replace/move cursor if any matches
// note the spacebands - this prevents duplicates
if (elem.innerHTML.match(/ test /)) {
preserveCaretPosition(function() {
elem.innerHTML = elem.innerHTML.replace(/ test /g, ' ' + replaceStart + 'test' + replaceEnd + ' ');
});
}
}, 500);
}

Categories

Resources