I have a page with couple of DIV elements. When user presses the CTRL+ENTER button combo, I need to display (via alert()) the text, that user previously selected. I found the solution and it works like a charm, but there is still one thing left.
I need to make event trigger, only when selected text is inside a DIV with class "main_content". I've tried to assign keyup to $('DIV.main_content'), but it does not work.
Is there a way to make event trigger only if text inside $('DIV.main_content') selected?
Here is a working code that triggers on the whole document:
// Get user selection text on page
function getSelectedText() {
if (window.getSelection) {
return window.getSelection();
}
else if (document.selection) {
return document.selection.createRange().text;
}
return '';
}
$(document).ready(function(){
$(document).keydown(function(e) {
if(e.which == 13 && e.ctrlKey) {
alert(getSelectedText());
return false;
}
});
});
See the code with markup in jsFiddle
You have an error in the getSelectedText() function: window.getSelection() returns a Selection object, not a string. The fact you're passing the result of this to alert() is masking this, because alert() implicitly converts the argument passed to it into a string.
Here's some code to check whether the selection is completely contained within a <div> element with a particular class. It works in all major browsers.
Live example: http://www.jsfiddle.net/cVgsy/1/
// Get user selection text on page
function getSelectedText() {
if (window.getSelection) {
return window.getSelection().toString();
}
else if (document.selection) {
return document.selection.createRange().text;
}
return '';
}
function isSelectionInDivClass(cssClass) {
var selContainerNode = null;
if (window.getSelection) {
var sel = window.getSelection();
if (sel.rangeCount) {
selContainerNode = sel.getRangeAt(0).commonAncestorContainer;
}
} else if (document.selection && document.selection.type != "Control") {
selContainerNode = document.selection.createRange().parentElement();
}
if (selContainerNode) {
var node = selContainerNode;
while (node) {
if (node.nodeType == 1 && node.nodeName == "DIV" && $(node).hasClass(cssClass)) {
return true;
}
node = node.parentNode;
}
}
return false;
}
$(document).ready(function(){
$(document).keydown(function(e) {
if(e.which == 13 && e.ctrlKey && isSelectionInDivClass("main_content")) {
alert(getSelectedText());
return false;
}
});
});
It is interesting question. I have the following idea: you need to catch mouseup event on div.
For example:
So, in your case you can do something like this:
var selectedText = "";
$(".yourdiv").mouseup(function(){
if (window.getSelection)
selectedText = window.getSelection();
else if (document.selection)
selectedText = document.selection.createRange().text;
alert(selectedText)
});
And variable selectedText will be store selected text.
Related
Here is a simple script function getSelectedText() that is working on button click. It means that when we select any text and click on the button, the function is creating a new NEWCLASS div successfully. But now I want to use a shortcut key, like CTRL+W to get selected text in the NEWCLASS div.
I tried this code but it doesn't work. Please, check it and let me know what mistake I am making here.
var input = document.getElementsByTagName("body")[0];
input.addEventListener("keyup", function(event) {
if (event.keyCode === 37) {
event.preventDefault();
document.getElementById("myBtn").click();
}
});
My code:
// Function to get the Selected Text
function getSelectedText() {
var selectedText = '';
// #### create a new element with variable (nw) #### //
var nw = document.createElement("div"); // Element's tag
nw.className = "NEWCLASS"; // Element's class name
// some applied style
// window.getSelection
if (window.getSelection) {
selectedText = window.getSelection();
}
// document.getSelection
else if (document.getSelection) {
selectedText = document.getSelection();
}
// document.selection
else if (document.selection) {
selectedText =
document.selection.createRange().text;
} else return;
// #### get the Selected text appended to body #### //
nw.innerHTML = selectedText;
document.getElementsByClassName('maintitle')[0].prepend(nw); // Append element to body
}
<button id="mybtn" onclick="getSelectedText()">Button</button>
<p>Select any part of this sentence and press the button. Select any part of this sentence and press the button. Select any part of this sentence and press the button</p>
<div class="maintitle"> </div>
the ctrl key with w will close the chrome browser so I used "Z" key for that you can replace the key code with whatever you want.
Find the keycodes here
const keySelected = new Set();
document.addEventListener('keydown', (e) => {
keySelected.add(e.which);
if(keySelected.has(17) && keySelected.has(90)){
getSelectedText();
}
});
document.addEventListener('keyup', (e) => {
keySelected.delete(e.which);
});
/*
//jquery code if anyone want
$(document).ready(function(){
const keySelected = new Set();
$(document).keydown(function (e) {
keySelected.add(e.which);
if(keySelected.has(17) && keySelected.has(90)){
getSelectedText()
}
});
$(document).keyup(function (e) {
keySelected.delete(e.which);
});
});
*/
// Function to get the Selected Text
function getSelectedText() {
var selectedText = '';
// #### create a new element with variable (nw) #### //
var nw = document.createElement("div"); // Element's tag
nw.className = "NEWCLASS"; // Element's class name
// some applied style
// window.getSelection
if (window.getSelection) {
selectedText = window.getSelection();
}
// document.getSelection
else if (document.getSelection) {
selectedText = document.getSelection();
}
// document.selection
else if (document.selection) {
selectedText =
document.selection.createRange().text;
} else return;
// #### get the Selected text appended to body #### //
nw.innerHTML = selectedText;
document.getElementsByClassName('maintitle')[0].prepend(nw); // Append element to body
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="mybtn" onclick="getSelectedText()">Button</button>
<p>
Select any part of this sentence
and press the button. Select any part of this sentence
and press the button. Select any part of this sentence
and press the button
</p>
<div class="maintitle"> </div>
You don't need to recall the event on the button, you should be capable of detect the press of the key you want and call the function, like:
document.addEventListener('keydown', (e) => {
if (e.ctrlKey && e.code === 'keyW') {
getSelectedText();
}
});
Ctrl+W is not such a good choice, as on Windows it is a common shortcut key for closing the current Window or document, so your script will not even get the key event.
But I'll pick Ctrl+Y instead.
You should not use the deprecated keyCode property -- nor the which property which another answer suggests -- notice the red notice in the MDN documentation.
It is even easier with the key property. And you can use the ctrlKey property to know whether the control key is down.
I would use the keydown instead of the keyup event, as you can then cancel any default effect of the key, with a call to cancelDefault.
document.addEventListener("keydown", (event) => {
if (event.ctrlKey && event.key == "y") {
event.preventDefault();
getSelectedText();
}
});
// Your original code:
function getSelectedText() {
var selectedText = '';
var nw = document.createElement("div"); // Element's tag
nw.className = "NEWCLASS"; // Element's class name
if (window.getSelection) {
selectedText = window.getSelection();
} else if (document.getSelection) {
selectedText = document.getSelection();
} else if (document.selection) {
selectedText = document.selection.createRange().text;
} else return;
nw.innerHTML = selectedText;
document.getElementsByClassName('maintitle')[0].prepend(nw);
}
<button id="mybtn" onclick="getSelectedText()">Button</button>
<p>Select any part of this sentence and press the button or enter Ctrl+Y.
Select any part of this sentence and press the button or enter Ctrl+Y.
Select any part of this sentence and press the button or enter Ctrl+Y.
</p>
<div class="maintitle"> </div>
This should work
var input = document.getElementsByTagName("body")[0];
input.keypress("w", function(event) {
if (event.ctrlKey) {
event.preventDefault();
document.getElementById("myBtn").click();
}
});
Im currently building a very simple inline-editor, for content editable areas within a website. I have managed to do the basics (Bold, Italic etc) and now I have hit a pitfall.
I'm allowing the user to create links, by highlighting text and creating the link via text input. My problem is if the highlighted/selected text is already wrapped in tags I wish the text input to display the current link. Thus giving the user the ability to terminate the link or update/edit it.
My code for creating a link by highlighting selected text HTML:
<div contenteditable='TRUE' class="editable">This Contenteditable text</div>
<!-- Add Url to Highlighted Text -->
<div class="text-button" unselectable="on" onmousedown="event.preventDefault();" onclick="displayUrlInserter();">Add Url</div>
<!-- Show URL Input and Submit -->
<div class="text-button-panel" id="text-button-panel">
<input type="text" id="url" placeholder="Paste or Type your link">
<div class="text-panel-done" onmousedown="event.preventDefault();" onclick="doneUrl()">Done</div>
<div class="text-panel-cancel" onmousedown="event.preventDefault();" onclick="cancelUrl()">Cancel</div>
</div>
Javascript :
function saveSelection() {
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
return sel.getRangeAt(0);
}
} else if (document.selection && document.selection.createRange) {
return document.selection.createRange();
}
return null;
}
function restoreSelection(range) {
if (range) {
if (window.getSelection) {
sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (document.selection && range.select) {
range.select();
}
}
}
var selRange;
function displayUrlInserter() {
selRange = saveSelection();
// Display
document.getElementById("text-button-panel").style.display = "block";
// Focus
document.getElementById("url").focus();
}
function doneUrl() {
var url = document.getElementById("url").value;
// No Url
if (url === "") {
return false;
}
// Check for HTTP
if (!url.match("^(http|https)://")) {
url = "http://" + url;
}
restoreSelection(selRange);
**// THIS IS WHERE I NEED TO CHECK FOR EXISTING A TAGS**
document.execCommand("CreateLink", false, url);
// Hide Panel
document.getElementById("text-button-panel").style.display = "none";
// Reset Input
document.getElementById("url").value = "";
}
function cancelUrl() {
document.getElementById("text-button-panel").style.display = "none";
}
The saveSelection and restoreSelection saves the currently selected text and allows me to create the link within doneUrl() via the execCommand.
This all works fine, all i need is to be able check and get the if it is present. Any guidance would be appreciated.
Try : Grande.js
https://github.com/mduvall/grande.js
Look like this when you selected texts
Live : http://mattduvall.com/grande.js/
Here is a function to check if the current selection is a link.
function itemIsLinked(){
if(window.getSelection().toString() != ""){
var selection = window.getSelection().getRangeAt(0);
if(selection){
if (selection.startContainer.parentNode.tagName === 'A' || selection.endContainer.parentNode.tagName === 'A') {
return [true, selection];
} else { return false; }
} else { return false; }
}
}
Then you can run something like
var isLink = itemIsLinked();
If it is linked it will return :
isLink[0] -> true
isLink[1] -> the link object.
To then get the HREF from that selection use:
isLink[1].startContainer.parentNode.href
That's worked really well for me. Good luck.
I have working code that inserts <br> when you hit enter in a content editable div. (Browsers have various defaults of inserting <div> or <p> instead)
The problem is that it kills the default behavior of hitting enter to add another list item when building ordered or unordered lists. So my question is, can you detect if the text insertion point is within a list item, and if so, disable the javascript that deals with the enter key?
Working code: http://jsfiddle.net/kthornbloom/RCdhS/
You need to do some DOM tree checking on the node containing the selection. Here's a demo that will work in all major browsers:
http://jsfiddle.net/CeMxs/2/
Code:
function isSelectionInsideElement(tagName) {
var sel, containerNode;
tagName = tagName.toUpperCase();
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount > 0) {
containerNode = sel.getRangeAt(0).commonAncestorContainer;
}
} else if ( (sel = document.selection) && sel.type != "Control" ) {
containerNode = sel.createRange().parentElement();
}
while (containerNode) {
if (containerNode.nodeType == 1 && containerNode.tagName == tagName) {
return true;
}
containerNode = containerNode.parentNode;
}
return false;
}
http://jsfiddle.net/RCdhS/2/
.on('keypress', 'document', function (e) {
if (!$('li').focus();) {
...
}
}
});
I am new to use html+javascript+jQuery. I am trying to use window.getSelection to get selected text but this is not working.
Can any one suggest solution for this.
Thanks in advance.
Just need simple line of code in java script which done your job
//I am using below line of code which works in both android and web browsers.
function getSelectedText() {
var selection = null;
if (window.getSelection) {
selection = window.getSelection();
} else if (typeof document.selection != "undefined") {
selection = document.selection;
}
var selectedRange = selection.getRangeAt(0);
console.log(selectedRange.toString());
}
NOTE : Don't call this method in post or inside any runnable interface as post or any runnable interface make delay in calling this method(Method call happens after browser selection release). Just call this method like
webView.loadUrl("javascript:getSelectedText()");
I know this is a very old question, but I get this as a first search result when I had tried to resolve the same or similar issue. I didn't find a solution here but after some time I realized that sometimes for phones there should be a short timeout between click and selection to make getSelection() work properly.
So e.g. instead this:
document.getElementById("element").addEventListener('click', function (event) {
window.getSelection().selectAllChildren(this)
});
You should use somethink like this:
document.getElementById("element").addEventListener('click', function (event) {
setTimeout(function(passedThis) {
window.getSelection().selectAllChildren(passedThis)
}, 10, this);
});
Maybe it save some time to somebody.
If you want to call a function right after a text selection, you can use the "selectionchange" event:
document.addEventListener("selectionchange", handleSelection);
It's working for android chrome and iOS safari.
Try
function getSelected() {
var text = "";
if (window.getSelection && window.getSelection().toString() && $(window.getSelection()).attr('type') != "Caret") {
text = window.getSelection();
return text;
} else if (document.getSelection && document.getSelection().toString() && $(document.getSelection()).attr('type') != "Caret") {
text = document.getSelection();
return text;
} else {
var selection = document.selection && document.selection.createRange();
if (!(typeof selection === "undefined") && selection.text && selection.text.toString()) {
text = selection.text;
return text;
}
}
return false;
}
Jsfiddle: http://jsfiddle.net/qTEmc/1/
I need to associate events with the keypress event on links which are added in the contenteditable.
If you try typing in the contenteditable area in the linked jfiddle, you'll see it creates a link and you can type within it. I fyou press return, you go to a newline. What I want is for pressing return in the new link to trigger a function. For the sake of progress, I'm just trying to get it to return an alert at the moment.
Does anyone know a reliable way to do this?
You won't be able to detect key events within the links themselves because they don't fire key events. Instead, you'll need to adapt your existing keypress handler for the contenteditable element to inspect the selection to see if it lies within a link. Here's a function to do that. I've also updated your demo.
function selectionInsideLink() {
var node = null, sel;
// Get the selection container node
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
node = sel.getRangeAt(0).commonAncestorContainer;
}
} else if (document.selection) {
sel = document.selection;
if (sel.type != "Control") {
node = sel.createRange().parentElement();
}
}
// Check if the node is or is contained inside a link
while (node) {
if (node.nodeType == 1 && node.tagName.toLowerCase() == "a") {
return true;
}
node = node.parentNode;
}
return false;
}