JavaScript not able to replace text with new text - javascript

I am trying to convert selected text's font with help of AngularJs and jQuery. This is my code. Everything is working fine but i am not able to change the text with a new text.
This is my code:
var app = angular.module('myApp', []);
app.controller('editor', function($scope) {
$scope.color = "black";
$scope.selectedText = "";
$scope.changeFont = function() {
if ($scope.selectedText != "") {
var changedText = "<span style='font-size:" + $scope.kys_selected_font + "px' >" + $scope.selectedText + "</span>";
alert($scope.selectedText + $scope.kys_selected_font + " " + changedText);
document.getElementById("#content").innerHTML.replace($scope.selectedText, changedText);
} else {
$("#content").append("<span id='one' style='font-size:" + $scope.kys_selected_font + "px' > this is some text </span>");
$("#one").focus();
}
};
$("#content").mouseup(function() {
$scope.selectedText = window.getSelection();
});
});

innerHTML.replace(...) returns a new string, rather than modifying the existing one, so your replacement won't modify the element.
You need to actually update the property:
var el = document.getElementById("content");
el.innerHTML = el.innerHTML.replace($scope.selectedText, changedText);
(also note # removed from element ID as per #IvanSivak's comment)

Related

HTML Appearing as Text in Oracle Apex when Highlighting Text in Textarea

I have a requirement for the user to highlight text as blue in a text area.
The html is not being applied to the text area and is instead printed as text.
Has anyone encountered and overcome this?
Thank you.
This is the code that I am using:
function ModifySelection () {
var textarea = document.getElementById("P85_30DAY");
if ('selectionStart' in textarea) {
// check whether some text is selected in the textarea
if (textarea.selectionStart != textarea.selectionEnd) {
//var newText = textarea.value.substring (0, textarea.selectionStart) +
// "[start]" + textarea.value.substring (textarea.selectionStart, textarea.selectionEnd) + "[end]" +
// textarea.value.substring (textarea.selectionEnd);
var opnSpan = '<span style="color:white;background-color:blue">';
var clseSpan = '</span>';
var begText = textarea.value.substring (0, textarea.selectionStart);
var endText = textarea.value.substring (textarea.selectionEnd);
var selText = opnSpan + textarea.value.substring (textarea.selectionStart, textarea.selectionEnd) + clseSpan;
//$("#P85_30DAY").html("<span>" + begText + "<span style='color:white;background-color:blue'> " + selText + "</span>" + endText + "</span>"); //appears as text
// textarea.value = begText + selText + endText; //appears as text
$("#P85_30DAY").val(begText + selText + endText); //appears as text
}
}
else { // Internet Explorer before version 9
// create a range from the current selection
var textRange = document.selection.createRange ();
// check whether the selection is within the textarea
var rangeParent = textRange.parentElement ();
if (rangeParent === textarea) {
textRange.text = "[start]" + textRange.text + "[end]";
}
}
}
document.getElementById("P85_30DAY").onkeyup = ModifySelection;
document.getElementById("P85_30DAY").onmouseup = ModifySelection;
This is the html for the element I am trying to highlight text in:
<textarea name="p_t07" class="textarea" id="P85_30DAY" style="width: 587px; height: 600px; font-size: 130%; margin-top: -431px; margin-left: -1340px; position: relative;" contenteditable="true" maxlength="4000" rows="1" cols="80" wrap="virtual"></textarea>
You can't use HTML inside of a textarea. It's an input field and will render anything inside of it as plain text.
Instead, have a look at ContentEditable which will allow you to render HTML inside of an editable element.
I got it to work folks.
Only one highlight selection can be made. I will keep working it but if anyone has any ideas for multiple highlight selection feel free to contribute.
$("#P85_30DAY").attr("contenteditable","true");
$("#P85_30DAY").css("postition","absolute");
function ModifySelection () {
var textarea = document.getElementById("P85_30DAY");
if ('selectionStart' in textarea) {
// check whether some text is selected in the textarea
if (textarea.selectionStart != textarea.selectionEnd) {
//var newText = textarea.value.substring (0, textarea.selectionStart) +
// "[start]" + textarea.value.substring (textarea.selectionStart, textarea.selectionEnd) + "[end]" +
// textarea.value.substring (textarea.selectionEnd);
var opnSpan = '<span style="color:white;background-color:blue">';
var clseSpan = '</span>';
var begText = textarea.value.substring (0, textarea.selectionStart);
var endText = textarea.value.substring (textarea.selectionEnd);
// var selText = opnSpan + textarea.value.substring (textarea.selectionStart, textarea.selectionEnd) + clseSpan;
var selText = textarea.value.substring (textarea.selectionStart, textarea.selectionEnd);
//$("#P85_30DAY").html("<span>" + begText + "<span style='color:white;background-color:blue'> " + selText + "</span>" + endText + "</span>"); //appears as text
// textarea.value = begText + selText + endText; //appears as text
// $("#P85_30DAY").html(begText + $("<span style='color:white;background-color:blue'></span>").text(selText) + endText); appears as object
//$("#P85_30DAY").val(begText + $("p").wrapInner("<span style='color:white;background-color:blue'></span>") + endText); appears as object
$("#P85_30DAY").empty(); //works for one highlight
$("<span>" + begText + "<span style='color:white;background-color:blue'>" + selText + "</span>" + endText + "</span>").appendTo("#P85_30DAY");
}
}
else { // Internet Explorer before version 9
// create a range from the current selection
var textRange = document.selection.createRange ();
// check whether the selection is within the textarea
var rangeParent = textRange.parentElement ();
if (rangeParent === textarea) {
textRange.text = "[start]" + textRange.text + "[end]";
}
}
}
//document.getElementById("P85_30DAY").onkeyup = ModifySelection;
document.getElementById("P85_30DAY").onmouseup = ModifySelection;

Google Docs Apps Script getBackgroundColor(Offset)

Let's say I have some sentences in Google Docs. Just one sentences as an example:
"My house is on fire"
I actually changed the background color so that every verb is red and every noun blue.
Now I want to make a list with all the verbs and another one with the nouns. Unfortunately getBackgroundColor() only seems to work with paragraphs and not with single words.
My idea was, to do something like this (I didn't yet have the time to think about how to do the loop, but that's not the point here anyway):
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var paragraphs = body.getParagraphs();
var colorVar = paragraphs[0].getText().match(/\w+/).getBackgroundColor(); // The regEx matches the first word. Next I want to get the background color.
Logger.log(colorVar);
}
The error message I get goes something like this:
"The function getBackgroundColor in the text object couldn't be found"
Thx for any help, or hints or comments!
You want to retrieve the text from a paragraph.
You want to retrieve each word and the background color of each word from the retrieved the text.
In this case, the color is the background color which is not getForegroundColor().
You want to achieve this using Google Apps Script.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
At first, the reason of your error is that getBackgroundColor() is the method of Class Text. In your script, getBackgroundColor() is used for the string value. By this, the error occurs.
In this answer, for achieving your goal, each character of the text retrieved from the paragraph is scanned, and each word and the background color of each word can be retrieved.
Sample script:
function myFunction() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var paragraphs = body.getParagraphs();
var textObj = paragraphs[0].editAsText();
var text = textObj.getText();
var res = [];
var temp = "";
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (c != " ") {
temp += c;
} else {
if (temp != "") res.push({text: temp, color: textObj.getBackgroundColor(i - 1)});
temp = "";
}
}
Logger.log(res) // result
}
When you run the script, the text of 1st paragraph is parsed. And you can see the result with res as an object.
In this sample script, the 1st paragraph is used as a test case. So if you want to retrieve the value from other paragraph, please modify the script.
References:
getBackgroundColor()
getBackgroundColor(offset)
editAsText()
If I misunderstood your question and this was not the direction you want, I apologize.
Here's a script your welcome to take a look at. It highlights text that a user selects...even individual letters. I did it several years ago just to learn more about how documents work.
function highLightCurrentSelection() {
var conclusionStyle = {};
conclusionStyle[DocumentApp.Attribute.BACKGROUND_COLOR]='#ffffff';
conclusionStyle[DocumentApp.Attribute.FOREGROUND_COLOR]='#000000';
conclusionStyle[DocumentApp.Attribute.FONT_FAMILY]='Calibri';
conclusionStyle[DocumentApp.Attribute.FONT_SIZE]=20;
conclusionStyle[DocumentApp.Attribute.BOLD]=false;
conclusionStyle[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT]=DocumentApp.HorizontalAlignment.LEFT;
conclusionStyle[DocumentApp.Attribute.VERTICAL_ALIGNMENT]=DocumentApp.VerticalAlignment.BOTTOM;
conclusionStyle[DocumentApp.Attribute.LINE_SPACING]=1.5;
conclusionStyle[DocumentApp.Attribute.HEIGHT]=2;
conclusionStyle[DocumentApp.Attribute.LEFT_TO_RIGHT]=true;
var br = '<br />';
var selection = DocumentApp.getActiveDocument().getSelection();
var s='';
if(selection) {
s+=br + '<strong>Elements in Current Selection</strong>';
var selectedElements = selection.getRangeElements();
for(var i=0;i<selectedElements.length;i++) {
var selElem = selectedElements[i];
var el = selElem.getElement();
var isPartial = selElem.isPartial();
if(isPartial) {
var selStart = selElem.getStartOffset();
var selEnd = selElem.getEndOffsetInclusive();
s+=br + 'isPartial:true selStart=' + selStart + ' selEnd=' + selEnd ;
var bgcolor = (el.asText().getBackgroundColor(selStart)=='#ffff00')?'#ffffff':'#ffff00';
el.asText().setBackgroundColor(selStart, selEnd, bgcolor)
}else {
var selStart = selElem.getStartOffset();
var selEnd = selElem.getEndOffsetInclusive();
s+=br + 'isPartial:false selStart=' + selStart + ' selEnd=' + selEnd ;
var bgcolor = (el.asText().getBackgroundColor()=='#ffff00')?'#ffffff':'#ffff00';
el.asText().setBackgroundColor(bgcolor);
}
var elType=el.getType();
s+=br + 'selectedElement[' + i + '].getType()= ' + elType;
if(elType==DocumentApp.ElementType.TEXT) {
var txt = selElem.getElement().asText().getText().slice(selStart,selEnd+1);
var elattrs = el.getAttributes();
if(elattrs)
{
s+=br + 'Type:<strong>TEXT</strong>';
s+=br + 'Text:<span style="color:#ff0000">' + txt + '</span>';
s+=br + 'Length: ' + txt.length;
s+=br + '<div id="sel' + Number(i) + '" style="display:none;">';
for(var key in elattrs)
{
s+= br + '<strong>' + key + '</strong>' + ' = ' + elattrs[key];
s+=br + '<input type="text" value="' + elattrs[key] + '" id="elattr' + key + Number(i) + '" />';
s+=br + '<input id="elattrbtn' + Number(i) + '" type="button" value="Save Changes" onClick="setSelectedElementAttribute(\'' + key + '\',' + i + ');" />'
}
s+='</div>Show/Hide';
}
}
if(elType==DocumentApp.ElementType.PARAGRAPH) {
var txt = selElem.getElement().asParagraph().getText();
var elattrs = el.getAttributes();
if(elattrs)
{
s+=br + '<strong>PARAGRAPH Attributes</strong>';
s+=br + 'Text:<span style="color:#ff0000">' + txt + '</span> Text Length= ' + txt.length;
for(var key in elattrs)
{
s+= br + key + ' = ' + elattrs[key];
}
}
}
s+='<hr width="100%"/>';
}
//var finalP=DocumentApp.getActiveDocument().getBody().appendParagraph('Total Number of Elements: ' + Number(selectedElements.length));
//finalP.setAttributes(conclusionStyle);
}else {
s+= br + 'No Elements found in current selection';
}
s+='<input type="button" value="Toggle HighLight" onclick="google.script.run.highLightCurrentSelection();"/>';
//s+='<input type="button" value="Exit" onClick="google.script.host.close();" />';
DocumentApp.getUi().showSidebar(HtmlService.createHtmlOutputFromFile('htmlToBody').append(s).setWidth(800).setHeight(450).setTitle('Selected Elements'));
}

Setting text input as a variable in Javascript

I'm trying to use my text input as a string variable and use that variable as a part of a URL to pull up JSON data but I can't seem to get it to work properly.
I don't know if I'm setting the variables incorrectly but any help would be appreciated. Thank you!
$(document).ready(function() {
var p = document.querySelector('p');
var input = document.getElementById('search').value;
$("#go").click(function() {
if (input === '') {
p.style.backgroundColor = 'transparent';
p.classList.add = 'hide';
p.innerHTML = '';
} else {
$.getJSON("https://en.wikipedia.org/w/api.php?action=opensearch&datatype=json&limit=5&search=" + input + "&callback=?", function(data) {
p.innerHTML = "<br> Click the links below";
p.classList.remove('hide');
var i = 0
for (i; i < 5; i++){
if (data[3][i] !== undefined){
p.innerHTML += '<h2> <a href ="' + data[3][i] + '" target = "_blank">' + data[1][i] + '<br>' + '<h3>' + data[2][i] + '</h3>' + '</h2>'
} else {
p.innerHTML = ' <h2> No matching result </h2>';
}
}
});
}
});
});
At the time you assign the variable value, it is empty because it is run when the site is loaded and there is probably no text in the search box yet. You want the content at the time #go is clicked, so just assign it inside the click event handler:
$(document).ready(function() {
var p = document.querySelector('p');
// the text field value is empty at this point
$("#go").click(function() {
// this is run when user clicks #go
var input = document.getElementById('search').value;
if (input === '') {
p.style.backgroundColor = 'transparent';
p.classList.add = 'hide';
p.innerHTML = '';
}
else {
// encode user input
$.getJSON("https://en.wikipedia.org/w/api.php?action=opensearch&datatype=json&limit=5&search=" + encodeURIComponent(input) + "&callback=?", function(data) {
p.innerHTML = "<br> Click the links below";
p.classList.remove('hide');
var i = 0
for (i; i < 5; i++){
if (data[3][i] !== undefined){
p.innerHTML += '<h2> <a href ="' + data[3][i] + '" target = "_blank">' + data[1][i] + '<br>' + '<h3>' + data[2][i] + '</h3>' + '</h2>'
}
else {
p.innerHTML = ' <h2> No matching result </h2>';
}
}
});
}
});
});
Additionally, you should always encode user input if you include it in a URI. Otherwise you'll experience unexpected behaviour when using any non alphanumerical character (including whitespace) in the search box. For a more detailed explanation of how and why, see the documentation.

How to apply style to selected text in CKEditor using JavaScript

I want to apply heading style (h1) to the selected text in CKEditor using JavaScript.
Here is my function:
function applyStyle()
{
var selection = CKEDITOR.instances.editor1.getSelection();
if(selection.getType() == 2) //where 2 will be Text type
{
var style = new CKEDITOR.style({element: 'h1'});
selection.applyStyle(style);
style.checkActive(editor1.elementPath(), editor1);
}
else
{
alert('Select text to apply');
}
}
But I can't get the style applied on the selected text,
Kindly someone solve this
Thanks
Its a cumbersome, but I found the solution for this ,see below
function applystyle(tagName)
{
var selection = CKEDITOR.instances.editor1.getSelection().getNative();
var oEditor = CKEDITOR.instances.editor1;
var openTag = "<" + tagName + ">";
var closeTag = "</" + tagName + ">";
var html = openTag + selection + closeTag;
var newElement = CKEDITOR.dom.element.createFromHtml( html, oEditor.document );
oEditor.insertElement( newElement );
}
I found the above code working well for me,
Thanks

Replace brackets to span javascript

I want to manipulate the DOM a bit and need some help.
That's my HTML-Markup:
<span class=“content“> This is my content: {#eeeeee}grey text{/#eeeeee} {#f00000}red text{/#f00000}</span>
That's how it should be:
<span class="content">This is my content: <span style="color:#eeeeee;">grey text</span><span style="color:#f00000;">red text</span></span>
The script should replace the brackets with span tags to change the font-color.
The color should the same that is in the bracket.
My approach:
function regcolor(element) {
var text = element.innerText;
var matches = text.match(/\{(#[0-9A-Fa-f]{6})\}([\s\S]*)\{\/\1\}/gim);
if (matches != null) {
var arr = $(matches).map(function (i, val) {
var input = [];
var color = val.slice(1, 8);
var textf = val.slice(9, val.length - 10);
var html = "<span style=\"color: " + color + ";\">" + textf + "</span>";
input.push(html);
return input;
});
var input = $.makeArray(arr);
$(element).html(input.join(''));
};
But it's not working very well and i'm not feeling good with the code, it looks messy.
And the script looses the content that's not in the brackets("This is my content:").
Anyone a idea?
I've used just a touch of jQuery, but it could easily do without. It's just a regular expression string replacement.
$('.content').each(function() {
var re = /\{(#[a-z0-9]{3,6})\}(.*?)\{\/\1\}/g;
// ^ ^
// $1 $2
this.innerHTML = this.innerHTML.replace(re, function($0, $1, $2) {
return '<span style="color: ' + $1 + '">' + $2 + '</span>';
});
});
I'm using a back-reference to properly match the opening and closing braces.
Update
Could be even shorter:
$('.content').each(function() {
var re = /\{(#[a-z0-9]{3,6})\}(.*?)\{\/\1\}/g,
repl = '<span style="color: $1">$2</span>';
this.innerHTML = this.innerHTML.replace(re, repl);
});
Look mum, no jQuery
var nodes = document.getElementsByClassName('content');
for (var i = 0, n = nodes.length; i < n; ++i) {
var re = /\{(#[a-z0-9]{3,6})\}(.*?)\{\/\1\}/g,
repl = '<span style="color: $1">$2</span>';
nodes[i].innerHTML = nodes[i].innerHTML.replace(re, repl);
}
Use the regex to replace the matches directly:
function regcolor2(element) {
var text = element.html();
var i = 0;
var places = text.replace(/\{(#[0-9A-Fa-f]{6})\}([\s\S]*)\{\/\1\}/gim, function( match ) {
var color = match.slice(1, 8);
var textf = match.slice(9, match.length - 10);
var html = "<span style=\"color: " + color + ";\">" + textf + "</span>";
return html;
});
$(element).html(places);
}
it can be shorter with jquery and this method or syntax
$(function() {
$('.content').html($('.content').text().replace( new RegExp('{(.*?)}(.*?){\/.*?}','g'), '<span style="color:$1">$2</span>'));
});

Categories