How can i get the id of the container (say, id of the p or div) of a user selected text?
I want to make list of selected texts, user selects a text then clicks on a button to add to the list.
And when user clicks the text from the list i want to highlight the place where original selection was made.
I need the id of the container because the selected text may not be unique and appear multiple times in the document.
i get the selected text like this Return HTML from a user-selected text
Here is one way it can be achieved cross browser (untested)
var getSelectionContainer = function() {
if (document.selection){ // IE
return document.selection.createRange().parentElement();
}
var select = window.getSelection();
if (select.rangeCount > 0) {
return select.getRangeAt(0).startContainer.parentNode;
}
};
Demo
(Select some text before 5 Seconds then look in the console)
Links
MDN window.getSelection
MDN selection.getRangeAt
MDN range.startContainer
MDN selection.rangeCount
window.getSelection().anchorNode - Gives you the DOM element where the selection started
window.getSelection().focusNode - Gives you the DOM element where the selection ended
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Selection?redirectlocale=en-US&redirectslug=DOM%2FSelection
Related
I use this code How can I position an element next to user text selection? to get the position of the selected text, but it doesn't work for the selected text inside an input. Sometimes the position is 0.
Is there some universal method for detecting the position of the selected text?
I want to show a tooltip on mouseup or dblclick the selected text.
You can use the following code to get the position of selected text:
var selection = window.getSelection();
var getRange = selection.getRangeAt(0);
getRect = getRange.getBoundingClientRect();
You can use getSelection api.
After selection a text run below code in console.
var selection = window.getSelection()
var baseOffset = selection.baseOffset
var length = selection.focusOffset -selection.baseOffset
var text = selection.focusNode.data.splice(baseOffset, length)
If you just need to get the position where the user doubleclicked, use the following snippet.
$('#thatInput').on('dblclick', function (e) {
alert('Position X: ' + e.clientX + '\nPosition Y: ' + e.clientY);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="thatInput">
The question is about getting the position of mouse pointer when selecting text. I am trying a solution that also works with keyboard events (choosed keyup).
I wrote a sample html page with a "vanilla" script inside to test the capabilities of the Selection API. This is the idea:
When selecting on text nodes, getting the position of selected text is done by means of the Range Object.
But when the selected text is a part of an Input Element, using the getBoundingClientRect() of the Range Object does not work (gave me a full zero ClientRect Object.
So, the function getSel() will try to consider both scenarios: selecting text just from the HTML or inside some input elements (just considered input and textarea).
On the bottom of the page there is a div#results element, for displaying data, then getSel() will create a new div#boundy with the coordinates of the ClientRect object or the related input element coordinates.
I wish to finish it, but I'm out of ideas on how to get the actual position of the selected text inside the input objects. It will have to be adding in a relative way to the coordinates of the element itself.
Answering Andrew, if this works, you'll be able to use the coordinates of div#boundy to place the tooltip wherever you want.
I've created a codepen here.
How can I get the multiple elements a user has selected from document.getSelection()?
document.getElementById("hello").onclick = function() {
selection = document.getSelection();
if(selection) {
console.log(selection.anchorNode.textContent);
}
};
http://jsbin.com/qisawudofa/edit?html,js,console,output
It seems to only return the element that was selected first, but in my case I need to get all of them.
Alternatively, is there a way to at least know when multiple elements have been selected?
You're probably most interested in the Ranges that make up the selection. Remember the user can make multiple selections all over the page. Each continuous area of selection will get its own instance of Range.
You'll need to iterate over all of the ranges. For each of them you can see where it starts and where it ends:
if (selection) {
for (i=0; i<selection.rangeCount; i++) {
range = selection.getRangeAt(i);
if (range) {
console.log(range.startContainer);
console.log(range.endContainer);
}
}
}
But for the example described in your code you'll need to consider two more things:
Only if the user very accurately selects a paragraph will you get the paragraph's node in startContainer. They might start their start selection even one character after the beginning of the paragraph and then you'll get a text node with the paragraph as its parent.
The Range only gives you the start and the end of the selection for that range. It doesn't directly give you all of the elements in between. So if the user selects more than 2 paragraphs, you'll need to figure out exactly which paragraphs are between start and end yourself.
I have two listbox, A & B:
when I double click on an item of A , the item will be added in List B. And i have done this. List B visually show the value, but when I go to the view source of the page, I dont see new <option>.
This is my List A options.
This is my List B options (before and after addition and it remains same whatever items added. this is my problem.):
It should have one <option>. like
<option value="VSNR">VSNR</option>
what is my code is :
$('#lstXLSCol').on('dblclick', function () {
var item = $('#lstXLSCol').find(":selected").text();
var newOption = { item: item };
$('option:selected', this).remove();
$.each(newOption, function (val, text) {
if (text != "")
$('#lstXLSSelectedCol').append(new Option(text, val));
});
});
EDIT 1 :
I have found it pressing F12 in IE. but the values are like below:
but, i wanted to insert the value same as text. What should be changed in my jquery code?
you can not see them. The source is just used to build the initial DOM that represents the document. Dynamically created elements are only inserted in the DOM.
But you can analyse such elements with a DOM viewer like Safari’s WebInspector or the Firefox extionsion Firebug. Firefox can also show source code that represents such dynamically created elements by selecting that element an choosing View Selection Source in the context menu.
See this
take out the space between params and :last
$('#lstXLSSelectedCol:last').html('<option value=\''+item+'\'>'+item+'</option><option>');
$('#lstXLSSelectedCol:last').live('change', function () {
var option_selected = $('option:selected', this).val();
$('#lstXLSSelectedCol:last').append($('<option>', {
value: option_selected
}).text(option_selected));
});
You won't see dynamically added elements in the source of your page.
Use your browser's console to inspect the DOM.
Normally it's enough to right click on the element and select "inspect" from the context menu, otherwise see this link for how to access your browser's console.
I am building a site where people can customize the shape of their product before they order it.
Ultimately there will be several buttons bound to four text boxes. As the user inputs higher values in the text box, the button that is activated changes so we know what size sheet of material will need to be ordered for this customer's design.
How can I create a button that is enabled/disabled based on the value placed in a text box?
You can use jQuery and try something like this:
First, give your buttons an attribute disabled="disabled", and then:
//Assuming they are typing, if it's a dropdown/select, see below
$('#input-id').on('keyup', function() {
if($(this).val() >= 10 && $(this).val() <= 20) { // If the value is between 10 and 20...
$('#button-id').removeAttr('disabled'); // Remove disabled attribute
} else { // If the value is not our keyword...
if(!$('#button-id').attr('disabled')) { // And the button is not disabled...
$('#button-id').attr('disabled', 'disabled'); // Readd disabled attribute
}
}
});
If you are using a dropdown or select box, use $("select option:selected").
Is it possible to detect what text has been selected in a text area using Javascript? I'm looking to show the user controls only when they have selected text
I've written a cross-browser function for getting the text selected in a textarea or text input and after some toing and froing the final version is I think the best one I've seen. I've posted it on Stack Overflow a few times before. Here's one example: Is there an Internet Explorer approved substitute for selectionStart and selectionEnd?
To detect when the user makes a selection in a textarea, you can use the select event:
var textarea = document.getElementById("some_id");
textarea.onselect = function() {
var selection = getInputSelection(textarea);
var selectedText = textarea.value.slice(selection.start, selection.end);
console.log("Selected text: " + selectedText);
};