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>
Related
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/
I am designing an chrome extension for Gmail. In this I want to get selected/highlighted text. I tried following code:
if (!window.x) {
x = {};
}
x.Selector = {};
x.Selector.getSelected = function() {
var t = '';
if($('.compose-container').getSelection){
t = $('.compose-container').getSelection();
alert(t);
} else if (window.getSelection) {
t = window.getSelection();
} else if (document.getSelection) {
t = document.getSelection();
} else if (document.selection) {
t = document.selection.createRange().text;
}
return t;
}
It is not giving me selected text in compose mail.
Please help me out.
You would need to use the copy command to achieve this.
var copyText = document.execCommand('copy');
Basically it will copy any text selection in the browser.
You can check out this link on how it was fully utilized
As per gRenzFries answer, I code same as link provided by him. But slight addition in code to paste it in textbox.
Code to Copy text :
var emailLink = document.querySelector('.gmail_default');
var range = document.createRange();
range.selectNode(emailLink);
window.getSelection().addRange(range);
try {
// Now that we've selected the anchor text, execute the copy command
var successful = document.execCommand('copy', true);
} catch(err) {
}
Code to paste it in textbox:
$('#text-to-display').val(""); //reset textbox value
$('#text-to-display').focus(); //set focus to textbox
document.execCommand("Paste");
This code works just as expected.
I my application i want to make the text seleected selected using mouse bold..How to do this using javascript?
Also how to know the cursor position using javascript...For example ,i may need to insert a text using my function just before the text where cursor is placed
You can do this in a textarea:
<html>
<head>
<title>onselect test</title>
<script type="text/javascript">
window.onselect = selectText;
function selectText(e)
{
start = e.target.selectionStart;
end = e.target.selectionEnd;
alert(e.target.value.substring(start, end));
}
</script>
</head>
<body>
<textarea>
Highlight some of this text
with the mouse pointer
to fire the onselect event.
</textarea>
</body>
</html>
Do you mean something like this:
function getSelText()
{
var txt = '';
if (window.getSelection)
{
txt = window.getSelection();
}
else if (document.getSelection)
{
txt = document.getSelection();
}
else if (document.selection)
{
txt = document.selection.createRange().text;
}
else { return; }
}
//txt is the selected text
Caching selected text, only available when it is editable input, but not in uneditable htm area i.e. when the text in div or span or etc. the above methods dosn't work .
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;
}