Show the focused div only bookmarklet - javascript

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.

Related

How do i copy text to clipboard - cross browser

Ok so feels like i have gone down a rabbit hole of how to copy text to clipboard on here and tried a lot of suggestions
seems easy to do it for chrome but that option doesn't work in other browsers
I have a few requirements
I would like to copy text to clipboard
to be able to copy a section of html with multiple elements
To work in safari and chrome at least
Vanilla Javascript
I have found this solution and it works except that it copies the html tags as well?
i tried changing the .innerHTML to .value on the button, but that comes back undefined
<div id="something">
<div>first name: <span class="name">name</span></div>
<div>Job title: <span class="job">job</span></div>
<div>Phone number: 0123456789</div>
<img class="companylogo" src="./img/example.jpg">
</div>
<button onclick="copyToClipboard(document.getElementById('something').innerHTML)">
Copy the stuff
</button>
<script>
/* copy function */
function copyToClipboard(textToCopy) {
var textArea;
function isOS() {
//can use a better detection logic here
return navigator.userAgent.match(/ipad|iphone/i);
}
function createTextArea(text) {
textArea = document.createElement('textArea');
textArea.readOnly = true;
textArea.contentEditable = true;
textArea.value = text;
document.body.appendChild(textArea);
}
function selectText() {
var range, selection;
if (isOS()) {
range = document.createRange();
range.selectNodeContents(textArea);
selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
textArea.setSelectionRange(0, 999999);
} else {
textArea.select();
}
}
function copyTo() {
document.execCommand('copy');
document.body.removeChild(textArea);
}
createTextArea(textToCopy);
selectText();
copyTo();
}
</script>
document.getElementById('something').innerHTML
sends html code inside #something to copyToClipboard and this behavior you mentiond is expected . what do you want to be copied to clipboard if not html ?
thanks Hosseind600 for trying to help
but i managed to find some code that does exactly what i would like it to do. whilst ticking off the requirements i had set
its currently the second answer but highest votes
How to copy text from a div to clipboard
<html>
<body>
<div id="a" onclick="copyDivToClipboard()"> Click to copy </div>
<script>
function copyDivToClipboard() {
var range = document.createRange();
range.selectNode(document.getElementById("a"));
window.getSelection().removeAllRanges(); // clear current selection
window.getSelection().addRange(range); // to select text
document.execCommand("copy");
window.getSelection().removeAllRanges();// to deselect
}
</script>
</body>
</html>

Wrap an html tag after clicking a toolbar button using js or jquery

I want to do something similar to what this website and wordpress does. When a user highlights text on the screen, then clicks a button on the toolbar it will wrap an html tag around the text. In jquery I would probably use the .wrap class but how would I detect if the user highlighted something.
For example, when the user writes Hello World then clicks on the bold button it will say <b>Hello World</b>
This mainly requires (1) accessing the selectionStart and selectionEnd properties of the input/textarea element and (2) replacing the substring of the value property across that range with the same text, but wrapped in the desired start and end tags. Also, I think it makes sense to reselect the replaced text, which requires a couple of calls to select() and setSelectionRange(). Also, if there's no selection (meaning start equals end) it's probably a good idea to do nothing at all.
window.selWrapBold = function(id) { selWrap(id,'<b>','</b>'); };
window.selWrapItalic = function(id) { selWrap(id,'<i>','</i>'); };
window.selWrap = function(id,startTag,endTag) {
let elem = document.getElementById(id);
let start = elem.selectionStart;
let end = elem.selectionEnd;
let sel = elem.value.substring(start,end);
if (sel==='') return;
let replace = startTag+sel+endTag;
elem.value = elem.value.substring(0,start)+replace+elem.value.substring(end);
elem.select();
elem.setSelectionRange(start,start+replace.length);
} // end selWrap()
<input type="button" value="bold" onclick="selWrapBold('ta1');"/>
<input type="button" value="italic" onclick="selWrapItalic('ta1');"/>
<br/>
<textarea id="ta1"></textarea>
Get the text of the html element which is wrapping the text, then add as html the text embedded in the <b> tag.
See jQuery DOM Manipulation for tutorials.
I used this question to get the selected text. And this question to
get the element with selected text in it. I combined them in a single function.
function updateHighlightedText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
var node = $(window.getSelection().anchorNode.parentNode); //Get the selected node
node.html(node.text().replace(text, "<b>"+text+"</b>")); //Update the node
}

execcommand on empty selection

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/

Knowing the text selected using mouse in javascript

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 .

Why can't this simple javascript/jquery code alert selected text?

I can't explain the behaviour of the code below. Here's my entire script
<html>
<head>
<script type="text/javascript" language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
var tmpText = '';
$(document).ready(function(){
tmpText = '';
$('#btn_bold').click(function(){alert(tmpText);});
$('textarea').bind('mouseup', function(){
tmpText = '';
if(window.getSelection){
tmpText = window.getSelection();
}else if(document.getSelection){
tmpText = document.getSelection();
}else if(document.selection){
tmpText = document.selection.createRange().text;
}
//tmpText = 'hello world';
alert(tmpText);
});
});
</script>
</head>
<body>
<button type="button" id="btn_bold">click</button>
<textarea>This is some text</textarea>
</body>
</html>
Try the following operations:
1) Use your mouse to high light text in the text area. You will notice that javascript alerts you the selected text.
2) Press the click button. You will notice javascript will alert you an empty string.
No uncomment tmpText = 'hello world'; and repeat the above steps. This time, you'll notice both steps 1) and 2) alerts you "hello world".
How come in the first experiment, step 2) does not alert you the same text as step 1)?
I am testing in google chrome
Because it doesn't automatically get converted to string. When you call it straight with alert(), it runs the toString on it, but when you assign to a variable to be later used, it keeps it as selection object and when you try to alert it later on, you presumably won't have that selection active anymore (because you just clicked the button).
Add toString() at the end of each of those selections and it should work as intended.
if(window.getSelection){
tmpText = window.getSelection().toString();
}else if(document.getSelection){
tmpText = document.getSelection().toString();
}else if(document.selection){
tmpText = document.selection.createRange().text;
}
example on jsfiddle
I recall this being explained quite well in the mozilla developer pages under the getSelection bit, if you want a better explanation why it is like this.
EDIT: found the link to the page on mozilla, specifically check what they say under "Notes".
In most browsers, the selection within a textarea (or text input) is handled differently to the selection in the main body of the page. To get the selected text within a textarea, you can use the following, which works in all major browsers:
jsFiddle: http://jsfiddle.net/fxN7p/
Code:
function getTextareaSelectedText(textarea) {
var text = "";
if (typeof textarea.selectionStart == "number") {
text = textarea.value.slice(textarea.selectionStart, textarea.selectionEnd);
} else if (typeof document.selection != "none" && document.selection.type == "Text") {
text = document.selection.createRange().text;
}
return text;
}
Hii...
you have to convert to string the selection... example
window.getSelection().toString()
otherwise you wont could access to the data

Categories