I've used this solution to select the text content for a code box using the code tag.
Jason's Answer which is the following:
function SelectText(element) {
var doc = document
, text = doc.getElementById(element)
, range, selection
;
if (doc.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
}
$(function() {
$('span').click(function() {
SelectText('selectme');
});
});
This is my code box:
<div class="codebox"><span>{L_CODE}: {L_SELECT_ALL_CODE}</span><div id="selectme"><code></code></div></div>
The problem is that when there are multiple code boxes in the same page, only the first one is selected because of the ID being the same.
How can I use a dynamic way so that when the users clicks to select the desired text, the clicked container will be selected regardless of how many boxes are present?
First of all, you should never have more than one element using the same ID (use the attributes CLASS or DATA for this purpose).
Then you just need to do:
$(".class").click(function(element) {
// Do crazy stuff with element
})
Or with the data attribute:
$("data[foo='blah']").click(function(element) {
// Do crazy stuff with element
})
Related
I want to create a CMS like wordpress. In my text editor I want the user to be able to create a hyperlink via a button click. But I don't want to show an alert so the user can input the url but a div shown under the selected word/sentence inside or over the text area with an text input. How do I get the location of the selected word?
I already tried to append a textnode to it like this:
window.getSelection().appendChild(document.createTextNode("testing"));
but I get an error, that .appendChild() is not a function.
$('#btnLink').click(function() {
window.getSelection().appendChild(document.createTextNode("testing"));
})
I expect the textnode is appended to the selected word, but it doesnt work
The getSelection() method will not return a node to append text to.
I've used some code from a different answer (added below the code) to achieve what you're asking.
$('#btnLink').click(function() {
var elm = getRange();
var div = document.createElement("div");
div.appendChild( document.createElement("input") );
elm.collapse(false);
elm.insertNode(div);
});
function getRange() {
var range, sel, container;
if (document.selection) {
range = document.selection.createRange();
range.collapse(isStart);
return range.parentElement();
} else {
sel = window.getSelection();
if (sel.getRangeAt) {
if (sel.rangeCount > 0) {
range = sel.getRangeAt(0);
}
} else {
// Old WebKit
range = document.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);
}
}
if (range) {
return range;
}
}
}
This code is copied and altered from How can I get the DOM element which contains the current selection? to demonstrate the use for this specific question.
A JSFiddle: https://jsfiddle.net/zuvq9nyc/5/
try this:
$('#btnLink').click(function() {
window.getSelection.append(document.createTextNode('testing'));
})
.appendchild() is a javascript function, jquery can't use it. use .append() instead and use .createTextNode() inside it.
I'm building a chrome extension where selected text can have different highlighting styles applied to it. I used ranges to get this all to work, and I clone the range, put a span around it, and then delete the range and replace it with the cloned one. Everything seems fine except I've somehow managed to disable right clicking by triggering this behavior through the extension. I've narrowed it down the single line of range.surroundContents(span), but here's the full code section:
// Determines the selected text
document.onmouseup = function() {
var selection = document.getSelection();
selection = getSelectedText(color);
};
// Finds the text selected in the page, spans it, and gives it a class
function getSelectedText(inputColor) {
var span = document.createElement('span');
span.setAttribute('class', inputColor);
if(document.getSelection) {
var selection = document.getSelection();
if(selection.rangeCount == true) {
var range = selection.getRangeAt(0).cloneRange();
range.surroundContents(span);
selection.removeAllRanges();
selection.addRange(range);
}
}
}
Is there a way I can counter this? I've already tried using document.oncontextmenu = false directly following the problem line, but that's not bringing back right click. I also tried replacing it with newNode.appendChild(range.extractContents()); range.insertNode(newNode) as recommended by https://developer.mozilla.org/en-US/docs/Web/API/Range/surroundContents but then instead of highlighting text, it seems to just be removing it from the page.
#wOxxOm answered my question in a comment, but a setTimeout() is what worked. So for anyone else who might have a similar issue in the future:
// Finds the text selected in the page, spans it, and gives it a class
function getSelectedText(inputColor) {
var span = document.createElement('span');
span.setAttribute('class', inputColor);
if(document.getSelection) {
var selection = document.getSelection();
if(selection.rangeCount == true) {
var range = selection.getRangeAt(0).cloneRange();
setTimeout(function(){
range.surroundContents(span);
selection.removeAllRanges();
selection.addRange(range);
}, 100)
}
}
}
I am trying to select an element's text on click using the following code:
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
Although the text is getting highlighted, empty string is copied to the clipboard on using Ctrl + C. Checking for selection.toString() returns an empty string too. Any idea why can this be happening?
Hm, I took a look at your code and tried:
var selection = window.getSelection();
var selectionText = selection.anchorNode.textContent
and I got the selected text content.
EDIT: it appears this was wrapped in a click function...one second.
$('<your selector goes here>').click(function(e) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(e.target);
selection.removeAllRanges();
selection.addRange(range);
console.dir(selection.anchorNode.textContent);
//text content should display...
//now that the content is highlighted, you can copy it
document.execCommand('copy');
})
I want to automatically select a piece of text so that the user can use ctrl + c to copy it to its clipboard.
In order to do this, I've attached some event handlers to a couple of inputs and a couple of divs (with tabindex="0").
However, if I select a piece of text with javascript, the browser indicates a selection but keeps the focus on the input.
If I try to achieve the same thing but with the div being the trigger, It works.
This behavior is only in FireFox.
In my jsfiddle (or in the snippet below) put the focus on the first input, press a random key (which selects the text), and try to copy paste it in the lower input.
Then try to do the same but with clicking the div. (clicking the div will also select the text).
var input = document.getElementById("my-input");
input.addEventListener("keydown", function(evt){
selectText(document.getElementById("selectme"));
});
var div = document.getElementById("clickme");
div.addEventListener("click", function(evt){
selectText(document.getElementById("selectme"));
});
var selectText = function(element){
var range, selection;
if(document.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if(window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
element.focus();
}
<input id="my-input"/>
<div id="selectme">Texttexttexttext</div>
<div tabindex="0" id="clickme">CLICK ME</div>
<input />
If you call evt.target.blur(); first, the input will lose its focus before focussing the div.
Your function will look like:
var input = document.getElementById("my-input");
input.addEventListener("keydown", function(evt){
evt.target.blur();
selectText(document.getElementById("selectme"));
});
I found the following code online which works well. I would like to use this on multiple elements on the same page and do not know how to do this. I can get the first to work but not the second.
Can anyone help?
Thanks,
John
Javascript:
function SelectText(element) {
var doc = document
, text = doc.getElementById(element)
, range, selection
;
if (doc.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
}
document.onclick = function(e) {
if (e.target.className === 'select') {
SelectText('some_text');
}
};
HTML:
<span id ='some_text'>Text to select </span><span class='select'>select</span>
<span id ='more_text'>More text to select</span><span class='select'>select</span>
Because you call function with same parameter.
SelectText('some_text');
"Text to select" will be selected no matter what class="select" you click.
Try this code:
function SelectText(element) {
var doc = document
, text = doc.getElementById(element)
, range, selection;
if (doc.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
}
document.onclick = function(e) {
if (e.target.className === 'select') {
SelectText(e.target.getAttribute('data-id'));
}
};
And change the HTML:
<span id ='some_text'>Text to select </span><span class='select' data-id="some_text">select</span>
<span id ='more_text'>More text to select</span><span class='select' data-id="more_text">select</span>
You can give a special attribute to each span with the id of the element you want to select:
//JS
SelectText(e.target.attributes["select"].value);
//HTML
<span class='select' select="some_text">select</span>
<span class='select' select="more_text">select</span>
Or, if the order of the elements is always similar and is not likely to change, you can retrieve the previous sibling:
SelectText(e.target.previousSibling.id);
For your case you can do:
SelectText(e.target.previousSibling.id);