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 .
Related
Below is my code. I want to highlight text on mouseup. I am new to Web. I have no idea why my code is not working. It is not highlighting any text.
Can someone help me in finding the problem? The code I have written is mostly what I have copied from here and there on web.
Problem 2: once the text is highlighted i want to open a menu on right click from mouse with 4 to 5 options and select one of them to label the highlighted text. Later download the labeled data in JSON format.
Firstly, I want to solve my first problem.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<style>
.red {
color: red;
}
;
</style>
<script>
thisRespondHightlightText(".select--highlight--active");
function thisRespondHightlightText(thisDiv) {
$(thisDiv).on("mouseup", function() {
var selectedText = getSelectionText();
var selectedTextRegExp = new RegExp(selectedText, "g");
var text = $(this).text().replace(selectedTextRegExp, "<span class='red'>" + selectedText + "</span>");
$(this).html(text);
});
}
function getSelectionText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
return text;
}
</script>
</head>
<body>
<div class="select--highlight--active">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</div>
</body>
</html>
change this, Jquery needs to be ready first
$(function() {
thisRespondHightlightText(".select--highlight--active");
});
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>
So I need to find a way to wrap the selected (highlighted) text in a web page into a specific tag using javascript or jQuery. I managed to wrap some text into the tag, but the problem is that whenever my selection includes two different paragraphs, the selected text becomes new paragraphs (i.e. everything becomes a mess). This is what I got (I am using the code inside a Google Chrome extension):
var sel = window.getSelection();
var rng = sel.getRangeAt(0);
var wrappingNode = document.createElement("myElement");
wrappingNode.appendChild(rng.extractContents());
rng.insertNode(wrappingNode);
I'm trying to find a way to prevent messing up the web page structure. Do you guys have any idea??
My objective is to apply a specific css style to this selected text.
Thank You!
FF only example because of range.createContextualFragment but something to work with. got to get to sleep!
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
.highlight {color: red; }
</style>
<script>
function highlight() {
var text, sel, range;
if (window.getSelection) {
text = window.getSelection().toString();
sel = window.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
range.insertNode(range.createContextualFragment('<span class="highlight">'+text+'</span>'));
}
} else if (document.selection && document.selection.createRange) {
text = document.selection.createRange().text;
range = document.selection.createRange();
range.innerHTML = '<span class="highlight">'+text+'</span>';
}
}
</script>
</head>
<body>
<p>lorem ipsum donor kebab</p>
<button onclick="highlight()">Click me</button>
</body>
</html>
I'm working on a specialized Text/HTML Editor with Javascript and JQuery in a contenteditable div. I implemented the different text styles (bold, italic,...) with execcommand. This seems to work only if the selected text is not empty. What is the best way to solve this problem?
Here an example of what I want to do with Text being the text in the editor, HTML being the corresponding html code and | being the cursor Position:
Text: Hello| World
HTML: <b>Hello| World</b>
By pressing a "bold" button, the execcommand('bold')-command should be executed on the selected position and the caret should be placed inside the modified position.
Text: Hello| World
HTML: <b>Hello</b>|</b> World</b>
This does not work. I found a Workaround by adding an text node containing a blank. This seems to work in Internet Explorer, but not in Firefox. Here a simple example:
HTML:
<div id="textcontent" contenteditable="true" overflow:auto;"><p>Enter text</p></div>
<button type="button" id="setBold">Bold</button>
Javascript:
$('#setBold').click(function () {
if (document.getSelection() != "") {
document.execCommand('bold');
}
else {
var selObj = document.getSelection();
var selRange = selObj.getRangeAt(0);
var newNode = document.createTextNode(' ');
selRange.deleteContents();
selRange.insertNode(newNode);
selObj.removeAllRanges();
selObj.addRange(selRange);
document.execCommand('bold');
selRange.deleteContents();
selObj.removeAllRanges();
selObj.addRange(selRange);
}
});
And the corresponding jsfiddle here: http://jsfiddle.net/andibioticum/3V7pK/
I modified my workaround-solution by inserting a text node containing a letter, calling the execcommand on that node, deleting it afterwards and setting the caret with focus().
$('#setBold').click(function () {
if (document.getSelection() != "") {
document.execCommand('bold');
}
else {
//get selected position
var selObj = document.getSelection();
//get range of selected position
var selRange = selObj.getRangeAt(0);
//Insert node with dummy text 'd'
var newNode = document.createTextNode('d');
selRange.insertNode(newNode);
selObj.removeAllRanges();
selObj.addRange(selRange);
//Execute command on dummy
document.execCommand('bold');
//Delete dummy from range
selRange.setStart(newNode, 0);
selRange.setEnd(newNode, 1);
selRange.deleteContents();
selObj.removeAllRanges();
selObj.addRange(selRange);
//Focus on empty element
$('#textcontent').focus();
}
});
See the fiddle here: http://jsfiddle.net/andibioticum/XJuRf/
I'm searching to select a text from a div, then click on a bookmarklet that remove all html parts in the body except the div where the text is selected
maybe jquery can help with something like :
javascript:var%20s=document.createElement('script');s.setAttribute('src',%20'http://jquery.com/src/jquery-latest.js');document.body.appendChild(s);s.onload=function(){/*the code*/};void(s);
Assuming the text you selected appears exactly once on the page this should work. If it appears multiple times this should show the last div on the page which contains the selected text.
More readable
function sel() {
if (window.getSelection) {
return window.getSelection().toString();
} else if (document.getSelection) {
return document.getSelection();
} else if (document.selection) {
return document.selection.createRange().text;
}
}
var s = document.createElement('script');
s.setAttribute('src', 'http://jquery.com/src/jquery-latest.js');
document.body.appendChild(s);
s.onload = function () {
var x = $(":contains('" + sel() + "')").last().parents("div").eq(0);
$("body").empty().append(x);
};
void(s);
As one-liner
javascript:function sel(){if(window.getSelection) return window.getSelection().toString();else if(document.getSelection) return document.getSelection();else if(document.selection) return document.selection.createRange().text;} var s=document.createElement('script');s.setAttribute('src','http://jquery.com/src/jquery-latest.js');document.body.appendChild(s);s.onload=function(){var x=$(":contains('"+sel()+"')").last().parents("div").eq(0);$("body").empty().append(x);};void(s);
If you also want the css stylings to be gone you must empty the <head> too
If i understood u right ur looking at something like this.
html
<body>
<div class="bookmarklet">
bookmarklet Text
</div>
<div>
<div>
<div class="bookmarklet">
bookmarklet Text
</div>
<div>Usless</div>
<div>Usless</div>
</div>
<div>Usless</div>
</div>
<script>
$('bookmarklet').unbind('click').bind('click',function(){
var text = $(this).text();
$('body').html('').append(text);
})
</script>
</body>
Now this will work if you have put the script tag for the jquery on the header if you don't know how to then comment below.