Appending Paragraph at specific location - javascript

I need to be able to change a string of text to heading1 and do some additional formatting later on. Caught up on this part for now. Here is my sample code as of right now.
function pocket() {
// Try to get the current selection in the document. If this fails (e.g.,
// because nothing is selected), show an alert and exit the function.
var selection = DocumentApp.getActiveDocument().getSelection();
var body = DocumentApp.getActiveDocument().getBody();
if (!selection) {
DocumentApp.getUi().alert('Cannot find a selection in the document.');
return;
}
var selectedElements = selection.getSelectedElements();
var selectedElement = selectedElements[0];
var pocketelement = selectedElement.getElement().getText();
body.appendParagraph(pocketelement).setHeading(DocumentApp.ParagraphHeading.HEADING1);
}
I need it to delete the original string and append the paragraph at the original strings location. Not sure how to do that. any help will be appreciated!

The body.appendParagraph() method appends the given paragraph, like javascript, to the body, at the end of it.
You are looking for the .insertParagraph(index, Paragraph). To get the index, try body.getChildIndex(paragraph). See the code below.
function pocket() {
// Try to get the current selection in the document. If this fails (e.g.,
// because nothing is selected), show an alert and exit the function.
var doc = DocumentApp.getActiveDocument();
var selection = doc.getSelection();
var body = doc.getBody();
if (!selection) {
DocumentApp.getUi().alert('Cannot find a selection in the document.');
return;
}
var selectedElements = selection.getSelectedElements();
var selectedElement = selectedElements[0];
//holds the paragraph
var paragraph = selectedElement.getElement();
//get the index of the paragraph in the body
var paragraphIndex = body.getChildIndex(paragraph);
//remove the paragraph from the document
//to use the insertParagraph() method the paragraph to be inserted must be detached from the doc
paragraph.removeFromParent();
body.insertParagraph(paragraphIndex, paragraph).setHeading(DocumentApp.ParagraphHeading.HEADING1);
};

Related

ParentNode returns the false value

I have some troubles with ParentNode
See I'm Working on a WYSIWYG and I want to tell me what are the parents of selected text.
It works fine till I have two Texts with diffrent style
for example :
<b>Bold<b> NotBold
When I click on Bold it returns BODY tag and when I click on it again It retruns B tag.
and Same about NotBold When I click on NotBold after I clicked on Bold It returns B tag and when I click this again it returns me BODY
Where is the problem ?
document.addEventListener("DOMContentLoaded",iFrameStart,false); //make iFrame Editable
function iFrameStart() {
iframe.document.designMode="On";
}
let frame = document.getElementById('iframe');
frame.contentWindow.onselectstart=function()
{
let frame = document.getElementById("iframe");
let select=frame.contentWindow.getSelection(); //get the selected text
let a = select.focusNode.parentNode; //get the parent of selected text
//if it removed it returns the value in " "
let array= ['ok']; //create an array
while (a) {
array.push(a); //add to the array
a=a.parentNode;
}
console.log(array); //display the parents
};
Please try the following. it is getting the parent node fine. You are not closing the tag in your example
<iframe id='iframe'></iframe>
document.addEventListener("DOMContentLoaded", iFrameStart, false); //make iFrame Editable
function iFrameStart() {
window.iframe.document.designMode = "On";
}
let frame = document.getElementById("iframe");
frame.contentDocument.body.innerHTML = "<b>Bold </b> <c>not bold</c>";
//window.iframe.document.getElementByTag("body")[0].innerHTML = "SAQIB";
frame.contentWindow.onclick = function() {
let frame = document.getElementById("iframe");
let select = frame.contentWindow.getSelection(); //get the selected text
let a = select.focusNode.parentNode; //get the parent of selected text
console.log(select.focusNode.parentNode);
//if it removed it returns the value in " "
let array = ["ok"]; //create an array
while (a) {
array.push(a); //add to the array
a = a.parentNode;
}
console.log(array); //display the parents
};

Google Apps Script problem using getLinkUrl(offset)

I'm trying to figure out how to use getLinkUrl(offset) in Google Apps Script.
I found the reference here - http://googlescriptreference.com/Document/Text/getlinkurloffset/, but I can't find any examples online.
This GAS returns Paragraphin the logs
var paragraph = tableCell.getChild(0);
This GAS returns the text string in the paragraph in the logs
var paragraphText = paragraph.getText();
This GAS returns NULL in the logs
var paragraphText = paragraph.getLinkUrl();
This GAS returns an error ( Cannot find method getLinkUrl(number).) and nothing in the logs
var paragraphText = paragraph.getLinkUrl(2);
Can someone please help me understand how to use the getLinkUrl(offset)?
Thanks for your help!
I was attempting to use the getLinkUrl(offset) directly on the paragraph element (not working example), but I needed to use asText() method before getLinkUrl(offset).
NOT Working
var paragraphText = paragraph.getLinkUrl(2);
Working
var paragraphText = paragraph.asText().getLinkUrl(2);
Google Document
https://docs.google.com/document/d/136G549zIYPYBndXs70ZnR_wEFg5fPST9ZGsOlTgmDyM/edit
//Works if link is on a word or words instead of entire paragraph
function myFunctionP1() {
//Find out how many Children there are
var body = DocumentApp.getActiveDocument().getBody();
Logger.log(body.getNumChildren());
//Find out which child is table
var table = body.getChild(2); //table is child#2
Logger.log(table);
//Find tableCell inside of table
var tableCell = table.getChild(0).getChild(0); //tableCell
Logger.log(tableCell)
//Find paragraph inside of tableCell
//I think, but I'm not sure, the HYPERLINK will be found somewhere within the PARAGRAPH element. But I can't figure out how to get to it.
var paragraph = tableCell.getChild(0); //paragraph element
Logger.log(paragraph)
//Get paragraph text
var paragraphText = paragraph.asText().getLinkUrl(2); //paragraph text
Logger.log(paragraphText)
}
//Works if link is on entire paragraph
//Works if link is on entire paragraph
//Works if link is on entire paragraph
function myFunctionP2() {
//Find out how many Children there are
var body = DocumentApp.getActiveDocument().getBody();
Logger.log(body.getNumChildren());
//Find out which child is table
var table = body.getChild(4); //table is child#2
Logger.log(table);
//Find tableCell inside of table
var tableCell = table.getChild(0).getChild(0); //tableCell
Logger.log(tableCell)
//Find paragraph inside of tableCell
//I think, but I'm not sure, the HYPERLINK will be found somewhere within the PARAGRAPH element. But I can't figure out how to get to it.
var paragraph = tableCell.getChild(0); //paragraph element
Logger.log(paragraph)
//Get paragraph text
var paragraphText = paragraph.getText(); //paragraph text
Logger.log(paragraphText)
//Get HYPERLIINK from paragraph text
var paragraphHYPERLINK = paragraph.getLinkUrl(); //paragraph text
Logger.log(paragraphHYPERLINK)
}
#Tanaike helped me find this solution.
https://stackoverflow.com/users/7108653/tanaike

Split div content at cursor position

I need to split an element after user clicks on it and the attr 'contenteditable' becomes 'true'. This fiddle works for the first paragraph but not second because the latter is in a p tag. Similary in this fiddle you will see that when the element has html tags in it, the counter loses accuracy and hence the text before and after the cursor is not what you'd expect.
The assumption here is that the users will split the data in a way that the help tags will stay intact. As pointed out by dandavis here, e.g. the div has <i>Hello</i> <b>Wo*rld</b>, the user will only need to split the div into two divs, first will have <i>Hello</i> and the second div will have <b>Wo*rld</b> in it.
Html:
<div><mark>{DATE}</mark><i>via email: </i><mark><i>{EMAIL- BROKER OR TENANT}</i></mark></div>
JS:
var $splitbut = $('<p class="split-but">Split</p>');
$(this).attr('contenteditable', 'true').addClass('editing').append($splitbut);
var userSelection;
if (window.getSelection) {
userSelection = window.getSelection();
}
var start = userSelection.anchorOffset;
var end = userSelection.focusOffset;
var before = $(this).html().substr(0, start);
var after = $(this).html().substr(start, $(this).html().length);
The "Split" button is not working as generating the html is not an issue once I get proper "after" and "before" text. Any ideas as to what I am doing wrong here?
Something like this could work for the specific case you describe
$('div, textarea').on('click', function(e) {
var userSelection;
if (window.getSelection) {
userSelection = window.getSelection();
}
var start = userSelection.anchorOffset,
end = userSelection.focusOffset,
node = userSelection.anchorNode,
allText = $(this).text(),
nodeText = $(node).text();
// before and after inside node
var nodeBefore = nodeText.substr(0, start);
var nodeAfter = nodeText.substr(start, nodeText.length);
// before and after for whole of text
var allExceptNode = allText.split(nodeText),
before = allExceptNode[0] + nodeBefore,
after = nodeAfter + allExceptNode[1];
console.log('Before: ', before);
console.log('------');
console.log('After: ', after);
});
Updated demo at https://jsfiddle.net/gaby/vaLz55fv/10/
It might exhibit issues if there are tags whose content is repeated in the whole text. (problem due to splitting)

unable to add html tags and associated data using jQuery

I have been using jQuery for a short period of time & currently I am working with a website where user will log in and then jQuery will get the data from the server and append it to the existing html code. I have searched a lot in stackoverflow for this and my current code is actually the summary of what I have learnt fro here. I have tried with the load function but later I saw it has been deprecated.
My intention is to add the data after the file is loaded or by any how enable users to see the data. I also need to add id so that I can get to add certain behavior for later. Both of this functions can be accessed from both html file (index.html and profile.html > profile.html will be loaded after login)
My code is given below.
function changePage(mainArray, length)
{
location.href="temp.html";
addData(mainArray, length);
}
$(function() {
function addData(mainArray, length)
{
alert("entry 1");
for(i = 0; i < length; i++)
{
var id1 = "h3"+i;
var id2 = "p"+i;
var newHeader= $('<h3></h3>'); //create a new h3
$(newHeader).attr('id', id1); //set the id attribute of newHeader
$(newHeader.html(mainArray["title"][i])); //set the innerHtml of the header
var newPara = $('<p></p>'); //create a new p
$(newPara).attr('id', id2); //set p id attribute
$(newPara).html(mainArray["desc"][i]); //add descr
$('#div1').append(newHeader);
$('#div1').append(newPara); //add them to dom.
}
$("h3").text("View Summary");
console.log("does it work?");
}
});
Your question could be a bit more descriptive, but my understanding is that you're performing an asynchronous request with jquery, then appending some elements to the DOM containing some part of the response. You reference 'adding data after file is loaded', that would probably mean you need to put your code inside of the basic document ready function of jquery:
$( document ).ready(function() {
//your code here
});
-shorthand version
$(function() {
//your code here
});
Now, the meat of your question is adding the elements after we get the data. Try something closer to this:
function addData(mainArray, length)
{
for(i = 0; i < length; i++)
{
var id1 = "h3"+i;
var id2 = "p"+i;
var newHeader= $('<h3></h3>'); //create a new h3
$(newHeader).attr('id', id1); //set the id attribute of newHeader
$(newHeader.html(mainArray["title"][i]); //set the innerHtml of the header
var newPara = $('<p></p>'); //create a new p
$(newPara).attr('id', id2); //set p id attribute
$(newPara).html(mainArray["desc"][i]); //add descr
$('#div1').append(newHeader);$('#div1').append(newPara); //add them to dom.
}
$("h3").text("View Summary");
console.log("does it work?");
}

how to select a text range in CKEDITOR programatically?

Problem:
I have a CKEditor instance in my javascript:
var editor = CKEDITOR.instances["id_corpo"];
and I need to insert some text programatically, and select some text range afterwards.
I already did insert text through
editor.insertHtml('<h1 id="myheader">This is a foobar header</h1>');
But I need to select (highlight) the word "foobar", programatically through javascript, so that I can use selenium to work out some functional tests with my CKEditor plugins.
UPDATE 1:
I've also tried something like
var selection = editor.getSelection();
var childs = editor.document.getElementsByTag("p");
selection.selectElement(childs);
But doesn't work at all!
How can I do that?
I think that
selection.selectRange()
could do the job, but I'could not figure out how to use it.
There are no examples over there :(
Get current selection
var editor = CKEDITOR.instances["id_corpo"];
var sel = editor.getSelection();
Change the selection to the current element
var element = sel.getStartElement();
sel.selectElement(element);
Move the range to the text you would like to select
var findString = 'foobar';
var ranges = editor.getSelection().getRanges();
var startIndex = element.getHtml().indexOf(findString);
if (startIndex != -1) {
ranges[0].setStart(element.getFirst(), startIndex);
ranges[0].setEnd(element.getFirst(), startIndex + findString.length);
sel.selectRanges([ranges[0]]);
}
You can also do the following:
get the current selection
var selection = editor.getSelection();
var selectedElement = selection.getSelectedElement();
if nothing is selected then create a new paragraph element
if (!selectedElement)
selectedElement = new CKEDITOR.dom.element('p');
Insert your content into the element
selectedElement.setHtml(someHtml);
If needed, insert your element into the DOM (it will be inserted into the current position)
editor.insertElement(selectedElement);
and then just select it
selection.selectElement(selectedElement);
Check out the selectElement() method of CKEDITOR.dom.selection.
http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.dom.selection.html
insert text at cursor point in ck editor
function insertVar(myValue) {
CKEDITOR.instances['editor1'].fire( 'insertText',myValue);
}
this is working for me

Categories

Resources