Reputation: 817
Is there a generic way in jQuery or JavaScript (most cross-browser compatible) to check if text has been highlighted?
I am working with an HTML <input type='text'>
element. This is a Search box that allows specific formats while searching for a Project.
A user can input the following:
On keydown I am filtering for various search formats. As it currently stands, if there are 10 characters entered, and they are all numeric, the input
textbox will only allow for more characters to be entered if they are non-numeric. The reason for this is, our project numbers are 10 digits long, and in the case that a user is searching for a project number, we want to capture only the first 10 characters and ignore the rest.
My goal is to allow for users to find a project by project number, highlight the text they just entered, and then search for another project by it's project number (replacing the existing search text). However, because we are filtering for non-numeric input, the numbers aren't captured.
Here is how I am filtering for non-numerics:
if ($input.val().length == 10 && !isNaN($input.val().replace(' ', '#'))) {
if ((e.which >= 48 && e.which <= 57) || (e.which >= 96 && e.which <= 105)) {
return false;
}
}
How can I modify this to ensure that if my text is highlighted, the input
will allow for numeric input to replace the existing query?
Upvotes: 2
Views: 10177
Reputation: 15104
You can use the Selection
object :
var selection = window.getSelection();
See the documentation here : https://developer.mozilla.org/en-US/docs/Web/API/Selection
With this object, you can check the selected dom node (anchorNode
). For example :
if ($(window.getSelection().anchorNode).attr('id') === 'something') { ... }
Upvotes: 8
Reputation: 11
Based on the above answer, here's the vanilla version.
document.addEventListener('click', function(){
if (window.getSelection().anchorNode.parentElement.classList.contains('word')) {
console.log('highlight');
}
});
I would change 'document' to the wrapping container and 'word' to whatever class/ID is on the text you want to detect a highlight on.
Upvotes: 1