I'm trying to replace the text in a TextArea with the contents of a string variable in a google chrome extension. But for some reason nothing changes in my result. Here's my code:
Content Script (js)
(function () {
// Holds text being selected in browser
var lwsSelectedText = '';
// Adds pop-up to current webpage
function lwsAddContent(callback) {
// Get body tag
var body = document.getElementsByTagName('body');
// add invisible div
document.body.innerHTML += '<div id="myModal" class="modal"><div class="modal-content"><span class="close">×</span><div id="lwsSpanishDiv"><p id="lwsSpanishTitle">Spanish</p><textarea id="lwsSpanishTextArea">Hello</textarea></div><div id="lwsEnglishDiv"><p id="lwsEnglishTitle">English</p><textarea id="lwsEnglishTextArea">Hello 2</textarea></div></div></div>';
callback(lwsSetUpTextGetter);
}
// Make the pop-up visible and set up close button
function lwsActivateContent(callback) {
var modal = document.getElementById('myModal');
// Get the textarea
var txtarea = document.getElementById("myTxtArea");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
span.onclick = function () {
modal.style.display = "none";
}
callback();
}
// Initialize ability to select and grab text from browser
function lwsSetUpTextGetter(callback) {
//Set the onmouseup function to lwsGetText
document.onmouseup = lwsGetText;
//Handling clicking outside webpage?
if (!document.all) document.captureEvents(Event.MOUSEUP);
}
//Gets selected text
function lwsGetText(e) {
// Get access to spanish text area
var spanishText = document.getElementById('lwsSpanishTextArea');
//Get text
lwsSelectedText = (document.all) ? document.selection.createRange().text : document.getSelection();
//if nothing is selected, do nothing
if (lwsSelectedText != '') {
// test: does browser grab text correctly?
alert(lwsSelectedText);
// Set spanish text area content to the selected text from browser
// --Error here: does not set text at all--
spanishText.innerHTML(lwsSelectedText);
}
}
// When document ready
$(document).ready(function () {
lwsAddContent(lwsActivateContent);
});
})();
When I use the extension, the pop-up loads, and when I highlight some text, lwsSelectedText populates with the correct text and it displays in the alert but it doesn't display in my text area. Am I accessing the contents of lwsSpanishTextArea wrong?
Thanks!
To set the value in an input, you can use the property value instead of innerHTML.
var lwsSelectedText = "Hello world!";
var spanishText = document.getElementById("spanishText");
spanishText.value = lwsSelectedText;
<textarea id="spanishText"></textarea>
Related
Change the selected word "TEST" with the ID of the Input "1"
With this code I am able to get the selected word and actually replace it with a hard coded dummy text but that only happens when I click inside the editor..
replaceSelection(event) {
var range = this.quill.getSelection();
if (range) {
if (range.length == 0) {
console.log('User cursor is at index', range.index);
} else {
var text = this.quill.getText(range.index, range.length);
console.log('User has highlighted: ', text);
this.quill.deleteText(range.index, range.length);
var clickedElement = event.target;
console.log(`clickedElement`, clickedElement)
// Get the id of the clicked element
var id = event.target.id;
console.log(`id:`);
this.quill.insertText(range.index, '{{' + id + '}}');
}
} else {
console.log('User cursor is not in editor');
}
}
}
When I click the Input ID this line is called:
console.log('User cursor is not in editor');
As said in API docs .getSelection will return null if editor has no focus. When you click on button that is not inside editor, you lose focus from editor.
However you can provide first argument, that will focus editor before getting selection range.
You just need to change your code to:
var range = this.quill.getSelection(true);
Editor will retain previous selection.
i have a button outside ckeditor, when clicked i want to insert a span element at caret position, this is what i have so far:
var el = document.querySelector('#editor');
ClassicEditor.create(el, {
licenseKey: ''
}).then( editor => {
appConfigs.editor = editor; //storing the editor for later usage
}).catch( error => {
//...
});
when the button is clicked i do:
function clickHandler(){
var editor = appConfigs.editor;
editor.model.change( writer => {
var html = '<span class="special-class-name" data-name="something">special word or button</span>';
var viewFragment = editor.data.processor.toView(html);
var modelFragment = editor.data.toModel(viewFragment);
var insertPosition = editor.model.document.selection.getFirstPosition();
editor.model.insertContent(modelFragment, insertPosition);
});
}
the code have the following issues:
1)the inserted span get stripped off all its attributes(class, data-name) which i want to preserve.
2)the editing caret doesn't go back automatically to the editor when the button clicked.
3)when i click the editor to restore caret and start typing, i noticed it edits the text inside inserted span, i want inserted span to be untouched and any further typing goes after it.
i will be so grateful if anyone could help me with those issues.
I'm creating a simple text editor in html and I have a function which allow user to insert website link into a text. Here is the code:
function setUrl() {
window.url = document.getElementById('txtFormatUrl').value;
window.sText = document.getSelection();
var urlanchor = document.createElement("A");
var urlatt = document.createAttribute("href");
urlatt.value = window.url;
urlanchor.setAttributeNode(urlatt);
window.sText = urlanchor;
}
How it works is that there will be a place to edit text and a box to enter URL. The user first highlighted the text then enter the URL, after that. The user presses the insert button which will called the setUrl() function.
But when I try, the URL didn't get inserted into the text, when open the F12 console, I saw that the element don't get insert. So what's wrong with my code?
Supposing that the element with ID txtFormatUrl is an <input> with a valid URL, the code is the following:
function setUrl() {
var url = document.getElementById('txtFormatUrl').value; // Get value from input tag
var selection = document.getSelection(); // Get info from text selected
if(selection.rangeCount) {
var textSelected = selection.toString(); // Get text selected
var element = document.createElement('a'); // Create a new anchor DOM node
element.innerText = textSelected; // Set de text selected to the new anchor DOM node
element.setAttribute('href', url); // Set a href value
var range = selection.getRangeAt(0); // Get selection range
range.deleteContents(); // Delete the current text
range.insertNode(element); // Replace the text
}
}
You can get more info here about replacing a selected text form another. Also, take a look at the DOM Range W3 specification or DOM Range MDN docs.
I started using clipboards.js to copy the content of a div with the click of the button but now I need to save it to a string so I can delete new lines to be shown like 1 paragraph but I cannot access to data that is stored to clipboard
this function here is to save to clipboard using clipboard.js and you can see I was trying to save it to "var str2" but it shows this "Cannot read property '_target' of undefined"
_this.testClick = function () {
var clipboard = new Clipboard('.clipboard');
var str2 = clipboard.clipboardAction._target.innerText.replace(/\n|\r/g, "");
_this.copyStringToClipboard(str2);
};
and this is the function that copies again but without spaces
_this.copyStringToClipboard = function (str) {
// Create new element
var el = document.createElement('textarea');
// Set value (string to be copied)
el.value = str;
// Set non-editable to avoid focus and move outside of view
el.setAttribute('readonly', '');
el.style = {
position: 'absolute',
left: '-9999px'
};
document.body.appendChild(el);
// Select text inside element
el.select();
// Copy text to clipboard
document.execCommand('copy');
// Remove temporary element
document.body.removeChild(el);
}
how can I access to inner text or clipboard so I can save it to str2?
Try using ClipboardJS() and success event
var clipboard = new ClipboardJS('.clipboard');
clipboard.on('success', function(e) {
console.log(e.text);
console.log(e.text.replace(/\n|\r/g, ""));
});
<script src="https://cdn.jsdelivr.net/npm/clipboard#2/dist/clipboard.min.js"></script>
<button class="clipboard" data-clipboard-text="Just
because
you can
doesn't mean you should — clipboard.js">
Copy
</button>
I am trying to impliment the IN Place Editing functionality using JQuery.
Here is the code
editinplace.js
$(document).ready(function() {
//When div.edit me is clicked, run this function
$("div.editme").click(function() {
//This if statement checks to see if there are
//and children of div.editme are input boxes. If so,
//we don't want to do anything and allow the user
//to continue typing
if ($(this).children('input').length == 0) {
//Create the HTML to insert into the div. Escape any " characters
var inputbox = "<input type='text' class='inputbox' value=\""+$(this).text()+"\">";
//Insert the HTML into the div
$(this).html(inputbox);
//Immediately give the input box focus. The user
//will be expecting to immediately type in the input box,
//and we need to give them that ability
$("input.inputbox").focus();
//Once the input box loses focus, we need to replace the
//input box with the current text inside of it.
$("input.inputbox").blur(function() {
var value = $(this).val();
$(".editme").text(value);
});
}
});
});
ButtonClickFunction.js
function ADDRADIOBUTTON(){
//Creating the div Tag
var answer_div = document.createElement("div");
answer_div.setAttribute("class", "answer");
answer_div.id = "answer_div_"+counter;
// Creating the Radio button tag
var answer_tag = document.createElement("input");
answer_tag.setAttribute("type", "radio");
answer_tag.id = "answer_tag_"+counter;
answer_tag.setAttribute("name", answer_div.id);
// Creating the Label Tag
var radio_label_tag = document.createElement("label");
radio_label_tag.setAttribute("for", answer_tag.id);
//Creating the label
var In_Place_Edit_div = document.createElement("div");
In_Place_Edit_div.setAttribute("class", "editme");
var In_Place_Edit = document.createTextNode("label");
In_Place_Edit_div.appendChild(In_Place_Edit);
radio_label_tag.appendChild(In_Place_Edit_div);
// Adding Radio button dot on the div and screen actually
answer_div.appendChild(answer_tag);
//Adding the Label here on the right of radio button.
answer_div.appendChild(radio_label_tag);
// Adding Answer div to the main div
var element=document.getElementById("divid_"+counter);
element.appendChild(answer_div);
}
and the index.php file includes these two JS files along with jquery-1.8.2.min.js
<script language="javascript" src="js/jquery-1.8.2.min.js"></script>
<script language="javascript" src="js/editinplace.js"></script>
<script type="text/javascript" src="js/ButtonClickFunction.js"></script>
What I am trying to do is create a radio button with label besides it and the label can be edited when we click on it. Now the problem here is that when I use the Code
<div class="editme">Please click me!!</div>
directly in the index.html page it works fine but when I try to generate the same line of code dynamically as I shown in ButtonClickFuction.js file it Does not work. What might be the problem ?
After crerating the HTML element dynamically you must bind the click function once more.Otherwise it wont work.Just call the click function after dynamic creation of the
< div class="edttime">Please click me!!.Otherwise click wont work for the newly created div with class edttime.
$("div.editme").click(function() {
//This if statement checks to see if there are
//and children of div.editme are input boxes. If so,
//we don't want to do anything and allow the user
//to continue typing
if ($(this).children('input').length == 0) {
//Create the HTML to insert into the div. Escape any " characters
var inputbox = "<input type='text' class='inputbox' value=\""+$(this).text()+"\">";
//Insert the HTML into the div
$(this).html(inputbox);
//Immediately give the input box focus. The user
//will be expecting to immediately type in the input box,
//and we need to give them that ability
$("input.inputbox").focus();
//Once the input box loses focus, we need to replace the
//input box with the current text inside of it.
$("input.inputbox").blur(function() {
var value = $(this).val();
$(".editme").text(value);
});
}