explorer: how to highlight text after using pasteHTML method? - javascript

i replace selected text with pasteHTML method (Pastes HTML text into the given text range, replacing any previous text and HTML elements in the range.) in internet explorer.
var ran = Editor.selection.createRange();
ran.pasteHTML('<span style="font-size:20px;">example</span>');
after replacing text, selection dissapears. how to highlight previous selection (text) again ? thanks

pasteHTML will delete the current selection from the document, so I assume you want to select the span you've replaced it with. To do this, add an ID to the span, move the TextRange to encompass its text and select it, as follows:
var ran = Editor.selection.createRange();
ran.pasteHTML('<span style="font-size:20px;" id="a_random_unique_id">example</span>');
var spanRange = ran.duplicate();
spanRange.moveToElementText( document.getElementById("a_random_unique_id") );
spanRange.select();

Related

Wrap plain text mouse selection into a html tag

I have an HTML element lets say a div which contains plain text. The text should be selectable and wrap the selection into a tag (mark for example). That is already working.
HTML Example:
<div class="highlighter-container">
This is a <mark>long</mark> sentence
</div>
Expected behaviour:
select text and wrap it into a tag ✓
selecting "is a long sentence" should not merge it into one tag
selection of "is a long sentence" should stop the selection at the mark tag which would be before "long" - you should not be able to select "is a long sentence"
Currently i'm using mouseup (on the .highlighter-container div) to trigger execute() then get the selection (using selection api) and replace it with the tag. I'm also disabling user selection with css user-select: none; on the mark tag but that doesn't stop the user from selecting further down the text.
My code so far:
Highlighter.prototype.execute = function() {
var selectedText = this.getSelectedText();
var rawText = selectedText.toString();
var range = selectedText.getRangeAt(0);
var highlighted = document.createElement('MARK');
highlighted.textContent = selectedText.toString();
highlighted.classList.add(HIGHLIGHTED_CLASS);
range.deleteContents();
range.insertNode(highlighted);
};
Highlighter.prototype.getSelectedText = function() {
var text = (document.all) ? document.selection.createRange().text : document.getSelection();
return text;
};
I tried a few things with the Range API but i'm not sure if its even possible by using the selection api.

Get highlighted text as a node in javascript

Working on a bit of javascript code; I'm wanting to alter the text when highlighted. The closest I've found currently is this: Get The Highlighted Selected Text. The problem with that solution though is it just gets the text that's highlighted as a string, but it's as a string. So I have the text, but I can't edit it like a node, doing innerHTML, change font, etc. It's just a string. I've got a solution that "works"™, but what is, is taking that string, and then searching for it. The problem is, if for example I highlight the string "the" in this post, I'd get a whole bunch of answers and no way to differentiate between them.
Is there a way to get selected text as a node?
You need to look for the selection (window.getSelection();)and get its range to have the right position of the selected text. Then you can apply styles by span-wrapping.
Take a look at
http://jsfiddle.net/jme11/bZb7V/
You can get an idea of how its done from this answer https://stackoverflow.com/a/3997896/5267669
Basically you get the selected text with the document.getSelection method, you delete it and in its place you insert your own content.
For example replace your selection with an H1 tag containing the text Added with js
sel = window.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
var h1 = document.createElement("h1");
h1.textContent = 'Added with js';
range.insertNode(h1);
}
You can select anything on this page, paste this code to the console and the selection will be replaced with an h1 tag

Select text and add a tag to it

There are a lot of question about this topic on SO but i can't seem to find any solution for my problem so i decide to ask my question. My situation is i have a dropdown list with several option and a textarea inside iframe. When user select some text in the textarea and choose one option from dropdown list then the selected text will have an a tag wrap around it and the option value will become tag href. Here my code:
var optionTag = document.getElementById("option-id");
var optionValue = optionTag.options[optionTag.selectedIndex].value;
var iframe = document.getElementById("my-frame");
var iframeContent = iframe.contentDocument.body.innerHTML.split("<br>")[0];
//get user selected text
var iframeSelection = iframe.contentWindow.getSelection().toString();
// and wrap a tag around it then add href equal to value of option
var aTag = "" + iframeSelection +"";
// replace user selected text with new a tag
iframe.contentDocument.body.innerHTML = iframeContent.replace(iframeSelection,aTag)
This code work but it only replace the first word if that word already exist. For example:
lorem ipsum click dolor sit amet click spum
If user select the second word "click" and choose one option then my code will replace the only the first word "click" and if i have several word "click" it still only replace the first word, but if user select the word "ipsum" or "lorem" then it work fine. I don't know how to fix this please help. Thank!
p/s:
I don't want to replace all the "click" word, i only want to replace exact piece user selected.
The problem is that iframeSelection in your replace() call is "click", not the element you previously selected, so it's replacing the first occurence.
Instead, try getting the range of your selection, deleting it and appending your new element to that range.
var selection = iframe.contentWindow.getSelection();
range = selection.getRangeAt(0);
range.deleteContents();
range.insertNode(document.createElement(your_new_element));
I couldn't test without your HTML, a JSFiddle would help.
The problem is that Javascript String.replace() only works like you expect when using it with a RegExp pattern with the global flag set. Luckily, this answer has a nice solution.
Change this:
iframe.contentDocument.body.innerHTML = iframeContent.replace(iframeSelection,aTag);
...into this:
iframe.contentDocument.body.innerHTML = iframeContent.replace( new RegExp(iframeSelection, 'g'), aTag );
What it does is that it converts your search string into a RegExp object with the global flag set, so each occurrence gets replaced.
If your intention was to only replace the exact piece the user had selected it gets more complex, but you can find all the required bits from this answer.

How to find the selection text beginning and end positions in Javascript?

I am trying to find the textual start and end of the selection. So, in the following text, if I selected "world! What a fine" from within "Hello, world! What a fine day it is!", I should get 7 as the start coordinate, and 24 as the end coordinate assuming a zero based index.
How is this achievable?
EDIT:
I am looking to find the selection of text that is not inside any <input> or <textarea> elements.
EDIT:
Decided the solution to use disabled <textarea>s
I use this:
/* Returns 3 strings, the part before the selection, the part after the selection and the selected part */
function getSelected()
{
var u = editor.val();
var start = editor.get(0).selectionStart;
var end = editor.get(0).selectionEnd;
return [u.substring(0, start), u.substring(end), u.substring(start, end)];
}
where editor is $("#editor") or whatever ID your textarea / input field may have.
Usage:
var select = getSelected()
editor.val(select[0] + '<h1>'+ select[2] + '</h1>' + select[1]);
Will wrap selected text in H1. If nothing is selected it will just add empty H1, but you can add checks and functionality to your liking.
** Not tested in all browsers, works in Chrome though **
This is possible but slightly complicated with contenteditable HTML content (as opposed to text within an <input> or <textarea> element). Here's a simple cross-browser implementation:
https://stackoverflow.com/a/4812022/96100
But I know a jQuery plugin that aims your problem and much more - https://github.com/localhost/jquery-fieldselection

Change some look for html on basis of selection of text

In my app there is an html file showed in a webview. I have a note functionality where when user selects text, it is highlighted and an image is added as suffix. This note is then saved as an html file.
So for this functionality, I have written a java script function.
function highlightsText()
{
var range = window.getSelection().getRangeAt(0);
var selectionContents = range.extractContents();
var newDate = new Date;
var randomnumber= newDate.getTime();
var div;
var imageTag = document.createElement("img");
imageTag.id=randomnumber;
imageTag.setAttribute("src","notes.png");
var linkTxt = document.createElement("a");
linkTxt.id=randomnumber;
linkTxt.setAttribute("href","highlight:"+randomnumber);
linkTxt.appendChild(selectionContents)
div = document.createElement("span");
div.style.backgroundColor = "yellow";
div.id=randomnumber;
linkTxt.appendChild(imageTag);
div.appendChild(linkTxt);
range.insertNode(div);
return document.body.innerHTML+"<noteseparator>"+randomnumber+"<noteseparator>"+range.toString();
}
Here I am making a span and this span holds my highlighted text with image.
Now problem is,
When I am selecting a paragraph, it only adds an image and does not highlight the text.
If I use div or p tag in place of span then it gives an entire line for a single word which looks rather odd.
Edit: div tags will get a linebreak before and after (usually, most browsers do this, considering it is a "division"/block level element), you're better off using a span.
And secondly you should append the selection contents to the span
ispain.appendChild(selectionContents) !! and do not forget the semicolon ;)
on a side note, you do know that:
1- you can't have html element ids starting with digits.
2- having more than one elements with the same id is gonna get unpredictable when you're selecting em.

Categories

Resources