Selecting Text through JavaScript - javascript

I want to select text thats is on a Html page and make it BOLD, I am using the following Code
<script type="text/javascript" >
function getSelectedText(){
if(window.getSelection){ ;
return window.getSelection().toString();
}
else if(document.getSelection){;
return document.getSelection();
}
else if(document.selection){ ;
return document.selection.createRange().text;
}
}
$(document).ready(function(){
$("*").live("mouseup",
function() {
selection = getSelectedText();
alert(selection);
if(selection.length >= 3) {
$(this).html($(this).html().replace(selection, "<b>" + selection + "</b>") );
}
}
);
});
</script>
This Code works Fine But when the text is in two different paragraphs/ Div or if there is a link between the text then it doesnt seem to work.
How Could i Make it Work ?

If you want to do some kind of highlighting of the current selection, using the built-in document.execCommand() is the easiest way. It works in all major browsers.
The following should do what you want on any selection, including ones spanning multiple elements. In non-IE browsers it turns on designMode, applies a background colour and then switches designMode off again.
UPDATE
Fixed to work in IE 9.
function makeEditableAndHighlight(colour) {
var range, sel = window.getSelection();
if (sel.rangeCount && sel.getRangeAt) {
range = sel.getRangeAt(0);
}
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
// Use HiliteColor since some browsers apply BackColor to the whole block
if (!document.execCommand("HiliteColor", false, colour)) {
document.execCommand("BackColor", false, colour);
}
document.designMode = "off";
}
function highlightSelection(colour) {
var range;
if (window.getSelection) {
// IE9 and non-IE
try {
if (!document.execCommand("BackColor", false, colour)) {
makeEditableAndHighlight(colour);
}
} catch (ex) {
makeEditableAndHighlight(colour)
}
} else if (document.selection && document.selection.createRange) {
// IE <= 8 case
range = document.selection.createRange();
range.execCommand("BackColor", false, colour);
}
}
document.onmouseup = function() {
highlightSelection("red");
};
Live example: http://jsfiddle.net/eBqBU/9/

a=document.getElementById('elementID').innerHTML;
variable 'a' will get the string value of anything inside the element with an id 'elementID'.
Is this ok?

Everything you need (based on your comments) can be found here: http://www.awesomehighlighter.com/webliter.js
I don't have time to extract the relevant parts but take a look for example in Webliter.prototype.highlight (just search for this in that file)
You can also use jQuery for example this plugin: http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html

Related

Javascript document.execCommand "bold" not working in chrome

I;m creating a text editor, and I'm using document.execCommand for styling purposes on my div, which is contend Editable. All other functions like underlining, italicizing, justifying, etc.. work, except for bold. I can't figure out why. Here is the code I'm using:
function makeEditableAndHighlight(styleType, optParam) {
if(typeof(optParam) == "undefined" || optParam == null){
optParam = null;
}
var range, sel = window.getSelection();
if (sel.rangeCount && sel.getRangeAt) {
range = sel.getRangeAt(0);
}
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
// Use HiliteColor since some browsers apply BackColor to the whole block
/*if (!document.execCommand("HiliteColor", false, colour)) {
document.execCommand("BackColor", false, colour);
}*/
document.execCommand(styleType, false, optParam);
document.designMode = "off";
}
function changeTextStyle(styleType, optParam){
if(typeof(optParam) == "undefined" || optParam == null){
optParam = null;
}
var range;
if (window.getSelection) {
// IE9 and non-IE
try {
/*if (!document.execCommand("BackColor", false, colour)) {
makeEditableAndHighlight(colour);
}*/
if (!document.execCommand(styleType, false, optParam)) {
makeEditableAndHighlight(styleType, optParam);
}
} catch (ex) {
makeEditableAndHighlight(styleType, optParam)
}
} else if (document.selection && document.selection.createRange) {
// IE <= 8 case
range = document.selection.createRange();
range.execCommand(styleType, false, optParam);
//range.execCommand("BackColor", false, colour);
}
}
I call it by using changeTextStyle("bold"); or whatever style inside the quotation marks.
This code has been working perfectly for every other style command, except bold. I'm calling it through the click of a button and it applies the style to the contenteditable div. I did get it to work once, and that was if the all the div contents were selected, other than that it won't work at all. any help would be nice, thanks!
Try this
<button id="bold" onclick="FormatText('bold');"> </button>
And for Save selection and Restore selection use following code
function saveSel() {
if (window.getSelection)//non IE Browsers
{
savedRange = window.getSelection().getRangeAt(0);
}
else if (document.selection)//IE
{
savedRange = document.selection.createRange();
}
}
//to restore sel
function restoreSel() {
$('#contenteditableId').focus();
if (savedRange != null) {
if (window.getSelection)//non IE and there is already a selection
{
var s = window.getSelection();
if (s.rangeCount > 0)
s.removeAllRanges();
s.addRange(savedRange);
}
else if (document.createRange)//non IE and no selection
{
window.getSelection().addRange(savedRange);
}
else if (document.selection)//IE
{
savedRange.select();
}
}
}
And call Savesel on Focusout event of your Contenteditable
$("#contenteditableId").focusout(function () {
saveSel();
});
At last Call restoreSel
function FormatText(command, option) {
restoreSel();
document.execCommand(command, false, option);
}
I use document.queryCommandState("bold"); for bold. It works for me.
I had a similar problem. In my case "span" tag makes an issue it has font-weight 700, After deep analysis, I figure out if span tag font weight is more than 500 (600, 700, 800, bold, bolder etc) create this issue, even if it's not inside "contenteditable" still it creates a problem. Just remove style font-weight 700 and add <b> instead resolve my issue. Hope it helps someone.

How to highlight selected text in web view in android

Below java script code is working in normal html, while using below script in android, it is not working.
Code
function highlight(colour) {
var range, sel;
if (window.getSelection) {
// Non-IE case
sel = window.getSelection();
if (sel.getRangeAt) {
range = sel.getRangeAt(0);
}
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
// Use HiliteColor since some browsers apply BackColor to the whole block
if ( !document.execCommand("HiliteColor", false, colour) ) {
document.execCommand("BackColor", false, colour);
}
document.designMode = "off";
} else if (document.selection && document.selection.createRange) {
// IE case
range = document.selection.createRange();
range.execCommand("BackColor", false, colour);
}
}
Please someone suggest me how to highlight selected text in webview.
Just a first check: Have you enabled Javascript?
this.webView.getSettings().setJavaScriptEnabled(true);

During string search using window.find() a dialog box appear

I am trying to search string and highlight those string. But during search a find dialog box appear. How can I disable the find dialog box ?
Here is my code -->
function doSearch(text) {
if (window.find && window.getSelection) {
document.designMode = "on";
var sel = window.getSelection();
sel.collapse(document.body, 0);
while (window.find(text)) {
document.execCommand("HiliteColor", false, "yellow");
sel.collapseToEnd();
}
document.designMode = "off";
} else if (document.body.createTextRange) {
var textRange = document.body.createTextRange();
while (textRange.findText(text)) {
textRange.execCommand("BackColor", false, "yellow");
textRange.collapse(false);
}
}
}
Firefox has a bug wherein it will display the find dialog box with window.find() if it has a blank argument:
https://bugzilla.mozilla.org/show_bug.cgi?id=672395
So if anyone is having this problem, you likely need to check the argument you're sending to window.find().

Using Javascript to change background-color back and forth?

I'm developing a Chrome Extension. I have this function here:
function makeEditableAndHighlight(colour) {
var range, sel = window.getSelection();
if (sel.rangeCount && sel.getRangeAt) {
range = sel.getRangeAt(0);
}
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
// Use HiliteColor since some browsers apply BackColor to the whole block
if (!document.execCommand("HiliteColor", false, colour)) {
document.execCommand("BackColor", false, colour);
}
document.designMode = "off";
}
function highlight(colour) {
var range, sel;
if (window.getSelection) {
// IE9 and non-IE
try {
if (!document.execCommand("BackColor", false, colour)) {
makeEditableAndHighlight(colour);
}
} catch (ex) {
makeEditableAndHighlight(colour)
}
} else if (document.selection && document.selection.createRange) {
// IE <= 8 case
range = document.selection.createRange();
range.execCommand("BackColor", false, colour);
}
}
I use it to highlight (background-color to yellow) a piece of selected text. The problem is with de-highlighting it.
I did this:
function body() {
document.getElementsByTagName("body")[0].addEventListener(
"click",
function(event){
highlight('transparent');
}
);
}
Problem with that is:
1) It requires the text to still be selected, but the click de-selects it, so it only works if you re-select the exact same text, and actually click ON IT.
2) It seems to make the page run much slower, even lock it at times.
What I would love to do is this:
When I click away, anywhere, the text is de-highlighted and de-selected (basically, set highlight to transparent or whatever it was before whenever the text gets de-selected).
What do?
P.S - Javascript only. If you have a way of using jQuery, let me know, but keep in mind I have to use it inside a content.js filed for a Chrome Extension.
use can use following code for unhighlighting. this will work fine. :)
document.designMode = 'on';
document.execCommand("undo", false, 'span');
document.designMode = 'off';
Here "span" is the element which is created by.
document.execCommand("HiliteColor", false, colour)

IE8 iframe DesignMode loses selection

The example below is a simple example of an iframe which uses window.parent.[turn designmode on] (this works). In FF all is well, but in IE8 (surprise surprise) any selection made is lost when you click out of the iframe. This totally negates the use of tools outside the iframe. I cannot find a solution 4 days later...
Open in IE8
http://www.chromedigital.co.za/hydrapage/test.htm
On any element in the main document you want not to break the iframe selection, add unselectable="on".
For example:
<div onclick="makeBold()" unselectable="on">Bold</div>
You could try saving the selection when the iframe loses focus. If you're sure the content of the iframe will not change before the user focuses on it again, you can store the currently selected Range or TextRange. The following script (for the main page) includes your original script, is not extensively tested and would be improved with better feature detection but is something to work with:
h_FF=!document.all
h_rt_F=0
function HLC_DM()
{
h_rt_F=document.getElementById("moo").contentWindow
if(h_FF)
{
if(h_rt_F.document.designMode!="on")
{
try
{
h_rt_F.document.designMode="on"
h_rt_F.document.execCommand("redo",false,null)
createEventHandlers();
}
catch(e)
{
setTimeout("HLC_DM",200)
return false
}
}
}
else
h_rt_F.document.body.contentEditable=true
createEventHandlers();
}
function getContentWindow() {
return document.getElementById("moo").contentWindow;
}
function saveSelection() {
var win = getContentWindow();
var doc = win.document;
var sel = win.getSelection ? win.getSelection() : doc.selection;
var range;
if (sel) {
if (sel.createRange) {
range = sel.createRange();
} else if (sel.getRangeAt) {
range = sel.getRangeAt(0);
} else if (sel.anchorNode && sel.focusNode && doc.createRange) {
// Older WebKit browsers
range = doc.createRange();
range.setStart(sel.anchorNode, sel.anchorOffset);
range.setEnd(sel.focusNode, sel.focusOffset);
// Handle the case when the selection was selected backwards (from the end to the start in the
// document)
if (range.collapsed !== sel.isCollapsed) {
range.setStart(sel.focusNode, sel.focusOffset);
range.setEnd(sel.anchorNode, sel.anchorOffset);
}
}
}
return range;
}
function restoreSelection(range) {
var win = getContentWindow();
var doc = win.document;
var sel = win.getSelection ? win.getSelection() : doc.selection;
if (sel && range) {
if (range.select) {
range.select();
} else if (sel.removeAllRanges && sel.addRange) {
sel.removeAllRanges();
sel.addRange(range);
}
}
}
var selectedRange;
function blurHandler() {
selectedRange = saveSelection();
}
function focusHandler() {
if (selectedRange) {
restoreSelection(selectedRange);
}
}
var iframeHandlersCreated = false;
function createEventHandlers() {
// Prevent setting up twice
if (!iframeHandlersCreated) {
var iframe = document.getElementById("moo");
var doc;
if (iframe.contentDocument && iframe.contentDocument.addEventListener) {
doc = iframe.contentDocument;
doc.addEventListener("blur", blurHandler, false);
doc.addEventListener("focus", focusHandler, false);
} else if (iframe.attachEvent) {
iframe.attachEvent("onbeforedeactivate", blurHandler);
iframe.attachEvent("onfocus", focusHandler);
}
iframeHandlersCreated = true;
}
}
My Editbox can add images, tables etc where you last clicked in the iframe and works for ie6, ie7 and FF but for ie8 it adds then at the start. They can then be cut and pasted to where you want them but that is a nuisance. MORE SERIOUS is that when I want to change the attributes of a table cell, for example, I have to have some text now in the cell which I must highlight or I can't determine what element I'm in!
Have Microsoft any bug fixes for the selection method or is Firefox or old versions of ie the only course?
regards Mike W

Categories