I'm trying to select a word from a text in a div. I'd like to click on a text and put a word beneath the mouse pointer to a variable for further processing.
function get_selection() {
var txt = '';
if (window.getSelection) {
txt = window.getSelection();
} else if (document.getSelection) {
txt = document.getSelection();
} else if (document.selection) {
txt = document.selection.createRange().text;
}
console.log(txt);
}
document.getElementById("txt").onclick = get_selection;
What I get in console is the whole paragraph:
Selection { anchorNode: #text ""My text is long and wise and it consumes a lot of interwebs."", anchorOffset: 18, focusNode: #text ""My text is long and strong and it consumes a lot of interwebs."", focusOffset: 18, isCollapsed: true, rangeCount: 1, caretBidiLevel: 0 }
...as opposed to the word that was clicked.
Please advise. I don't want to use jQuery.
You forgot to apply .toString to txt:
function get_selection() {
var txt = '';
if (window.getSelection) {
txt = window.getSelection().toString();
} else if (document.selection) {
txt = document.selection.createRange().text;
}
document.getElementById("out").innerHTML = txt;
}
document.getElementById("txt").onclick = get_selection;
<div id="txt">"My text is long and wise and it consumes a lot of interwebs."</div>
<div id="out"></div>
You need to add toString to your getSelection:
console.log(txt.toString());
Jsfiddle: https://jsfiddle.net/h8u1a6ha/
Related
I'm trying to make a simple text editor so users can be able to bold/unbold selected text. I want to use Window.getSelection() not Document.execCommand(). It does exactly what I want but when you bold any text, you can't unbold it. I want it in a way that I can bold and unbold any selected text. I tried several things but no success.
function addBold(){
const selection = window.getSelection().getRangeAt(0);
const selectedText = selection.extractContents();
const span = document.createElement("span");
span.classList.toggle("bold-span");
span.appendChild(selectedText);
selection.insertNode(span);
};
.bold-span {font-weight: bold;}
<p contentEditable>Bold anything here and unbold it</p>
<button onclick="addBold()">Bold</button>
This is close to what you want but groups words together so an unselect will remove from whole word. I have not been able to complete this as I have to go, but should be a good starting point.
function addBold(){
const selection = window.getSelection().getRangeAt(0);
let selectedParent = selection.commonAncestorContainer.parentElement;
//console.log(parent.classList.contains("bold-span"))
//console.log(parent)
let mainParent = selectedParent;
if(selectedParent.classList.contains("bold-span"))
{
var text = document.createTextNode(selectedParent.textContent);
mainParent = selectedParent.parentElement;
mainParent.insertBefore(text, selectedParent);
mainParent.removeChild(selectedParent);
mainParent.normalize();
}
else
{
const span = document.createElement("span");
span.classList.toggle("bold-span");
span.appendChild(selection.extractContents());
//selection.surroundContents(span);
selection.insertNode(span);
mainParent.normalize();
}
//selection is set to body after clicking button for some reason
//https://stackoverflow.com/questions/3169786/clear-text-selection-with-javascript
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}
};
.bold-span {font-weight: bold;}
<p contentEditable>Bold anything here and unbold it</p>
<button onclick="addBold()">Bold</button>
var span = '';
jQuery(function($) {
$('.embolden').click(function(){
var highlight = window.getSelection();
if(highlight != ""){
span = '<span class="bold">' + highlight + '</span>';
}else{
highlight = span;
span = $('span.bold').html();
}
var text = $('.textEditor').html();
$('.textEditor').html(text.replace(highlight, span));
});
});
You could define a function like this where the name of your class is "embolden"
I am working in HTML with jquery.
I want to make a webpage to highlight some text lines (line nos 15, 22, 32) in that page at a time. This can be done by left click in mouse and drag that line, so that the text line is selected with blue background.
I am able to get the selected lines as follows using jquery,
function getText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
console.log('text-----------'+text)
}
When I am clicking other line, first selected line was disappears. I need that line also be available. (In MSword, we can hold ctrl and drag the lines and it will be available)
For multiple selection, I know there is more plugins available in web. But I am looking for doing this selection using Javascript or jquery.
This is what I am looking for to do in my page, want to select texts and get them in my javascript function.
How may we do this?
This answer is combined of some issues.
Get the selection text
Mark it.
Copy to clipboard
It's not the full solution but there are all the parts.
So:
var output = '';
$('#test').mouseup(function () {
output += getSelectedText();
highlightSelected();
copyOutput();
$('#result').html(output);
});
function getSelectedText() {
if (window.getSelection) {
return window.getSelection().toString();
} else if (document.selection) {
return document.selection.createRange().text;
}
return '';
}
function highlightSelected() {
var SelRange;
if (window.getSelection) {
SelRange = window.getSelection().getRangeAt(0);
} else if (document.getSelection) {
SelRange = document.getSelection().getRangeAt(0);
} else if (document.selection) {
SelRange = document.selection.createRange();
}
if (SelRange.pasteHTML) {
SelRange.pasteHTML('<span class="hilited1">' + SelRange.text + '</span>');
}
else {
var newNode = $('<span class="hilited1" />')[0];
SelRange.surroundContents(newNode);
}
}
function copyOutput() {
var emailLink = document.querySelector('#result');
var range = document.createRange();
range.selectNode(emailLink);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
try {
var successful = document.execCommand('copy');
} catch (err) {
console.log('Oops, unable to copy');
}
window.getSelection().removeAllRanges();
}
textarea {
width:100%;
height:150px;
}
.hilited1 {
background:red;
color:#fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">I am working in HTML with jquery.
I want to make a webpage to highlight some text lines (line nos 15, 22, 32) in that page at a time. This can be done by left click in mouse and drag that line, so that the text line is selected with blue background.
I am able to get the selected lines as follows using jquery,
</div>
<hr />
<div id="result"></div>
<hr />
<textarea placeholder="Try to paste here"></textarea>
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to use the Javascript to add/remove the CSS/colour style to the html page?
I have a question on the HTML and javascript. I got the following paragrahe.
function add_span(){
// ??
}
<input type="button" onclick="add_span()" value="add span"/>
<p> statement1, statement2, statement3 </p>
Is it possible to have the following result after the user
select the highlighted text by mouse
click the button
e.g.
highlight the 'statement1,'
click the button
Expected Result:
<input tupe="button" onclick="add_span()" value"add span"/>
<p> <span class="ABC">statement1,</span> statement2, statement3 </p>
##### Updated Code, but no work
// updated code in the add_span
var selectedText;
if (window.getSelection)
{
selectedText = window.getSelection();
}
else if (document.getSelection) // FireFox
{
selectedText = document.getSelection();
}
else if (document.selection) // IE 6/7
{
selectedText = document.selection.createRange().text;
}
//create the DOM object
var newSpan = document.createElement('span');
// add the class to the 'spam'
newSpan.setAttribute('class', 'ABC');
document.getElementById('text').appendChild(newSpan);
var selectedTextNode = document.createTextNode();
newSpan.appendChild(selectedTextNode);
You can get selected text from #Pezhvak IMV's answer:
var selectedText;
if (window.getSelection)
{
selectedText = window.getSelection();
}
else if (document.getSelection) // FireFox
{
selectedText = document.getSelection();
}
else if (document.selection) // IE 6/7
{
selectedText = document.selection.createRange().text;
}
To add a element, you have to create a DOM node, set its attributes and add the element:
Create a DOM node:
var newSpan = document.createElement('span');
Set the class
newSpan.setAttribute('class', 'ABC');
Add the span to under the <p> (The <p> should have a id or some mechanism of identifying it:
<p id="text">
Add the <span> to under the <p>
document.getElementById('text').appendChild(newSpan);
And set the text
newSpan.innerHTML = selectedText;
You can also use createTextNode (alternative for step 5)
var selectedTextNode = document.createTextNode();
newSpan.appendChild(selectedTextNode);
To answer part of you question:
function getSelText() {
var txt = '';
if (window.getSelection)
{
txt = window.getSelection();
}
else if (document.getSelection) // FireFox
{
txt = document.getSelection();
}
else if (document.selection) // IE 6/7
{
txt = document.selection.createRange().text;
}
else return; document.aform.selectedtext.value = txt; }
I've created a simple tool so employees can personalize their company email signature. This tool creates some styled text with some bolded fonts and a bit of color, nothing fancy. If I then select the text and copy and paste it into my Gmail signature field all works well. It retains the formatting. However, I'd prefer to give the user the option of clicking a "Copy" button that copies the formatted content onto their clipboard.
I'm currently using ZeroClipboard to add the "copy to clipboard" functionality and it's working great. Thing is I don't know how to grab that formatted text. It just keeps copying the unformatted version. One thing I tried was adding a mouseDown listener to ZeroClipboard that selects the text like this:
function selectText() {
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(document.getElementById('clicktocopy'));
range.select();
}
else if (window.getSelection) {
var range = document.createRange();
range.selectNode(document.getElementById('clicktocopy'));
window.getSelection().addRange(range);
}
}
Then returns the selection like this:
function getText() {
if (window.getSelection) {
var range = window.getSelection();
return range.toString();
}
else {
if (document.selection.createRange) {
var range = document.selection.createRange();
return range.text;
}
}
}
However, this is only copying the unformatted text. Is it possible to copy the text formatted?
My formatted text is in a div with the id "results".
If you want an HTML string representing the current selection, the following function will do this (replacing your getText() function):
function getSelectionHtml() {
var html = "";
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
return html;
}
I'm trying to write a function that allows a contenteditable div to do some auto formatting while the user is typing in the div. So far I only manage to make it work in IE. Anyone can help me?
function formatOnKeyUp(){
if (window.getSelection) {
// ???????
} else if (document.selection) {
cursorPos=document.selection.createRange().duplicate();
clickx = cursorPos.getBoundingClientRect().left;
clicky = cursorPos.getBoundingClientRect().top;
}
text = document.getElementById('div1').innerHTML;
text = text.replace(/this/gm, "<i>this</i>");
// .... some other formating here...
document.getElementById('div1').innerHTML = text;
if (window.getSelection) {
// ????????
} else if (document.selection) {
cursorPos = document.body.createTextRange();
cursorPos.moveToPoint(clickx, clicky);
cursorPos.select();
}
}
You could use the selection save and restore module in my Rangy library, which uses invisible marker elements at the selection boundaries. I'd also suggest doing the replacement after a certain period of keboard inactivity rather than on every keyup event:
function formatText(el) {
// Save the selection
var savedSel = rangy.saveSelection();
// Do your formatting here
var text = el.innerHTML.replace(/this/gm, "<i>this</i>");
el.innerHTML = text;
// Restore the original selection
rangy.restoreSelection(savedSel);
}
var keyTimer = null, keyDelay = 500;
document.getElementById('div1').onkeyup = function() {
if (keyTimer) {
window.clearTimeout(keyTimer);
}
keyTimer = window.setTimeout(function() {
keyTimer = null;
formatText(document.getElementById('div1'));
}, keyDelay);
};
The cursor position and text range stuff looks particular to Microsoft's JScript.
If you're replacing text as someone types, why do you need that code?