I have a UIWebView i want to introduce functionality of content(may be text or text and images) selection so that the user can email it.
Is there any way to get the HTML code for the given selection using JavaScript?
I tried the built-in clipboard of webkit but its seems not working for images selection.May be i am wrong,if there is a way please tell me.
var range, frag, sel = window.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(0);
frag = range.cloneContents();
}
This will give you a DocumentFragment containing the selected content. You can traverse the descendants of the fragment using the usual DOM methods. If you must have a literal HTML string, you could then do the following:
var div = document.createElement("div");
div.appendChild(frag);
alert(div.innerHTML);
Note that this last part won't work if the selected contents can't be placed inside a <div> (if, say, the whole body or document was selected).
Related
I can insert html into a contenteditable div just fine using this code:
function insertHtmlAtCursor(html) {
let selection, range, node;
selection = window.getSelection();
if (selection.getRangeAt && selection.rangeCount) {
range = window.getSelection().getRangeAt(0);
node = range.createContextualFragment(html);
range.insertNode(node);
}
}
However, afterwards the cursor is placed within the inserted html. Instead I need it to be positioned just after the inserted html. Any ideas?
It seems like https://developer.mozilla.org/en-US/docs/Web/API/Range/setEndAfter e.g. range.setEndAfter(node); range.collapse(); might do. Or even https://developer.mozilla.org/en-US/docs/Web/API/Selection/collapseToEnd selection.collapseToEnd();.
I have been trying to build a web based text editor. And as part of the process, I am trying to dynamically create and modify elements based and keystroke events for font editing. In this particular jsfiddle example I'm trying to create a strong element upon hitting CTRL+b and setting the focus/caret inside the strong element so that subsequent text entered will be part of the bold element and hence will have bold text. But my code is just creating a strong element but not transferring the focus hence no text is getting bolder.
In the below code I'm creating event listener to capture keystroke events
p=document.getElementsByTagName("p")[0];
//console.log(p)
// adding eventlistener for keydown
p.addEventListener("keydown",listener);
// eventlistenerr callback function
function listener(){
e=window.event;
if(e.ctrlKey && e.keyCode==66)
{
console.log("CTRL+B");
// creating bold element
belm=document.createElement("strong");
belm.setAttribute("contenteditable","true")
p.appendChild(belm);
//bug below
// setting focus inside bold element
setfocus(belm,0);
e.preventDefault();
}
}
Here is the function for setting the focus.
function setfocus(context, position){
var range = document.createRange();
position =position || 0;
var sel = window.getSelection();
range.setStart(context, position);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
context.focus();
}
However, I have not doubt that the function which sets focus is faulty, because in the fiddle if you observe, I have created a separate setup just to test this
out. Click on the button "Click Here" and the focus dynamically shifts to paragraph element without any hassle. I am unable to figure out what is going wrong.
It's pretty much impossible to move the cursor into an empty element in a contenteditable div. However, as shay levi suggested in another post, you can insert the zero-width character ÈB into your empty element to give it an index value.
Here's an example*:
function insertNode(nodeName) {
var sel = window.getSelection(),
range;
range = sel.getRangeAt(0);
range.deleteContents();
var child = document.createElement(nodeName);
child.innerHTML = '';
range.insertNode(child);
}
var div = document.querySelector('div'),
btn = document.querySelector('button');
btn.addEventListener('click', function() {
insertNode('strong');
div.focus();
});
div.focus();
<div contenteditable></div><button><strong>B</strong></button>
*For the sake of simplicity, this script doesn't toggle bold text, it only sets it.
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
I'm trying to replace selected text with another text with a function switchText called from the context menu.
function switchText(info) {
var text = info.selectionText; // selected text
// then I do some manipulations with 'text' and get 'text_to_replace'
var text_to_replace = "some text"; // text to replace
}
alert(text) and alert(text_to_replace) works fine, but I'm trying to replace selected text right on the page but I can't figure out how to do it. I tried different methods but they hadn't worked. Any special permissions needed? I'm sorry if it's stupid question, I'm beginner in JS.
If you want to be able to do this anywhere on a page, you need to be able to set some kind of identifying ID to your selection. You have to do this through a content script of some kind. You can read more about it in the Chrome Developer documentation.
This code will allow you to change the text of a single selection
(tested in Chrome only)
function switchText(id) {
// Gets the selection range
// This is from Tim Down, linked below
var range, sel = window.getSelection();
if (sel.rangeCount && sel.getRangeAt) {
range = sel.getRangeAt(0);
}
// Creates a new node range
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
// This is from user YeppThatsMe, also linked below
document.execCommand("insertHTML", false, "<span id='own-id'>"+ document.getSelection()+"</span>");
document.designMode = "off";
// You can use either a variable or a string
var someNewText = "-- You can make this whatever you want --";
// Finds the new span and replaces the selection with your new text
document.getElementById("own-id").innerHTML=someNewText;
};
Sourced scripts
Tim's script
HTML5 inserCommand
Last Note
I didn't spend too long testing, and the script as-is will only change one selection per page. You'll need to tweak the way the function gets the tag and attribute info (change it to getElementsByClassName?) to run it more than once, but this should work.
to update a html element targeted by Id
document.getElementById("idtotarget").innerHTML = switchText(document.getElementById("idtotarget").innerHTML)
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.