Edited to clarify requirements
I am trying to simulate a click in a div through browser scripting.
The div I am working on is :
<div id="myid" class="myclass" hidefocus="true" aria-label="Message Body" g_editable="true" role="textbox" aria-multiline="true" contenteditable="true" tabindex="1">hello how</div>
The problem is that I am able to trigger a focus but I wanted a drop down to appear that only appears after a click has been made. The focus is occuring but I cannot simulate the click. My requirement is to use Javascript alone.
What I have tried:
document.getElementById("id1").dispatchEvent(new Event("click"));
document.getElementById(":16b").focus();
document.getElementById(":16b").selectionStart = 5;
var el = document.getElementById("editable");
var range = document.createRange();
var sel = window.getSelection();
range.setStart(el.childNodes[0], 5); //edit the offset here...e.g 5 offsets cursor
by 5 char
sel.removeAllRanges();
sel.addRange(range);
el.focus();
We have an editable div and we want to change the style of the text, selected by the user, on clicking our button; just same as this editor's bold or italic button.
But when we click on the button our selected text get deselected.
So how to keep our selected text highlighted even if the focus from the editable is off and change the style.
My Code :
Editable Div:
var textbox= document.createElement("div");
textbox.setAttribute("contenteditable", "true");
Button :
var bold = document.createElement("div");
bold.innerHTML = "B";
Button Click:
bold.addEventListener("click", function(){
getSelectedText();
},false);
function getSelectedText()
{
var html = "";
if (window.getSelection) {
html = window.getSelection().toString();
}
else if (document.selection && document.selection.type != "Control") {
html = document.selection.createRange().text;
}
alert(html);
}
You can get the selection by listening to your contentEditable's onmouseup and store it in a variable. After you clicked a div, you restore the selection to back what it was:
Javascript:
var range = "";
function getSelected() {
var selection = window.getSelection()
range = selection.getRangeAt(0);
}
function reselect() {
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
jsfiddle DEMO
used a button and a div for buttons so you can see the difference.
Either use the mousedown event instead of the click event or set the <div> button to be unselectable.
See this answer for details.
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
})
I’m building a simple text editor for Safari only. I need to implement a very specific behavior:
First enter - Creates <br> tag
Second enter (after <br>) - Create new paragraph
I’m already listening for enter on keypress event and using formatBlock to format paragraphs. How can I check if element before caret is a <br> element, so I can use formatBlock?
By default, Safari adds <div><br></div> on enter keypress, so I need to use preventDefault for first enter too. (code above)
I create new paragraphs using:
$("#content").live("keypress", function(e){
if (e.which == 13) {
document.execCommand("formatBlock", false, "p");
}
});
I can add br's using: ( Make a <br> instead of <div></div> by pressing Enter on a contenteditable )
if (window.getSelection) {
var selection = window.getSelection(),
range = selection.getRangeAt(0),
br = document.createElement("br");
range.deleteContents();
range.insertNode(br);
range.setStartAfter(br);
range.setEndAfter(br);
range.collapse(false);
selection.removeAllRanges();
selection.addRange(range);
return false;
}
UPDATE: User is typing a paragraph like this: <p>This is my paragraph</p>. At enter keypress, code should be <p>This is my paragraph<br></p> (cursor after br). Pressing enter for second time should result on <p>This is my paragraph</p><p></p> (cursor on second paragraph)
You could use keydown, for example:
<div id="textarea"></div>
Then in your script file:
document.getElementById("textarea").addEventListener("keydown",function(e){if(e.keyCode == 32) {ocument.getElementById("textarea").innerHTML+="<br />"} })
And your other stuff
DISCLAIMER: This is tested only on Chromium.
var sel = window.getSelection();
var range = sel.getRangeAt(0);
if ((sel.extentNode.previousElementSibling instanceof HTMLBRElement)
&& range.startOffset == 0)
{
// Do your magic to start a paragraph.
} else {
// Your existing code to add a <br> element since there is no <br> before it.
}
I have a textbox and a link button.
When I write some text, select some of it and then click the link button, the selected text from textbox must be show with a message box.
How can I do it?
When I click the submit button for the textbox below, the message box must show Lorem ipsum. Because "Lorem ipsum" is selected in the area.
If I select any text from the page and click the submit button it is working, but if I write a text to textbox and make it, it's not. Because when I click to another space, the selection of textbox is canceled.
Now problem is that, when I select text from textbox and click any other control or space, the text, which is selected, must still be selected.
How is it to be done?
OK, here is the code I have:
function ShowSelection()
{
var textComponent = document.getElementById('Editor');
var selectedText;
if (textComponent.selectionStart !== undefined)
{ // Standards-compliant version
var startPos = textComponent.selectionStart;
var endPos = textComponent.selectionEnd;
selectedText = textComponent.value.substring(startPos, endPos);
}
else if (document.selection !== undefined)
{ // Internet Explorer version
textComponent.focus();
var sel = document.selection.createRange();
selectedText = sel.text;
}
alert("You selected: " + selectedText);
}
The problem is, although the code I give for Internet Explorer is given on a lot of sites, I cannot make it work on my copy of Internet Explorer 6 on my current system. Perhaps it will work for you, and that's why I give it.
The trick you look for is probably the .focus() call to give the focus back to the textarea, so the selection is reactivated.
I got the right result (the selection content) with the onKeyDown event:
document.onkeydown = function (e) { ShowSelection(); }
So the code is correct. Again, the issue is to get the selection on click on a button... I continue to search.
I didn't have any success with a button drawn with a li tag, because when we click on it, Internet Explorer deselects the previous selection. The above code works with a simple input button, though...
Here's a much simpler solution, based on the fact that text selection occurs on mouseup, so we add an event listener for that:
document.querySelector('textarea').addEventListener('mouseup', function () {
window.mySelection = this.value.substring(this.selectionStart, this.selectionEnd)
// window.getSelection().toString();
});
<textarea>
Select some text
</textarea>
<a href="#" onclick=alert(mySelection);>Click here to display the selected text</a>
This works in all browsers.
If you also want to handle selection via the keyboard, add another event listener for keyup, with the same code.
If it weren't for this Firefox bug filed back in 2001 (yes, 14 years ago), we could replace the value assigned to window.mySelection with window.getSelection().toString(), which works in IE9+ and all modern browsers, and also gets the selection made in non-textarea parts of the DOM.
function disp() {
var text = document.getElementById("text");
var t = text.value.substr(text.selectionStart, text.selectionEnd - text.selectionStart);
alert(t);
}
<TEXTAREA id="text">Hello, How are You?</TEXTAREA><BR>
<INPUT type="button" onclick="disp()" value="Select text and click here" />
For Opera, Firefox and Safari, you can use the following function:
function getTextFieldSelection(textField) {
return textField.value.substring(textField.selectionStart, textField.selectionEnd);
}
Then, you just pass a reference to a text field element (like a textarea or input element) to the function:
alert(getTextFieldSelection(document.getElementsByTagName("textarea")[0]));
Or, if you want <textarea> and <input> to have a getSelection() function of their own:
HTMLTextAreaElement.prototype.getSelection = HTMLInputElement.prototype.getSelection = function() {
var ss = this.selectionStart;
var se = this.selectionEnd;
if (typeof ss === "number" && typeof se === "number") {
return this.value.substring(this.selectionStart, this.selectionEnd);
}
return "";
};
Then, you'd just do:
alert(document.getElementsByTagName("textarea")[0].getSelection());
alert(document.getElementsByTagName("input")[0].getSelection());
for example.
I am a big fan of jQuery-textrange.
Below is a very small, self-contained, example. Download jquery-textrange.js and copy it to the same folder.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>jquery-textrange</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="jquery-textrange.js"></script>
<script>
/* Run on document load */
$(document).ready(function() {
/* Run on any change of 'textarea' **/
$('#textareaId').bind('updateInfo keyup mousedown mousemove mouseup', function() {
/* The magic is on this line **/
var range = $(this).textrange();
/* Stuff into selectedId. I wanted to
store this is a input field so it
can be submitted in a form. */
$('#selectedId').val(range.text);
});
});
</script>
</head>
<body>
The smallest example possible using
<a href="https://github.com/dwieeb/jquery-textrange">
jquery-textrange
</a><br/>
<textarea id="textareaId">Some random content.</textarea><br/>
<input type="text" id="selectedId"></input>
</body>
</html>
// jQuery
var textarea = $('#post-content');
var selectionStart = textarea.prop('selectionStart');
var selectionEnd = textarea.prop('selectionEnd');
var selection = (textarea.val()).substring(selectionStart, selectionEnd);
// JavaScript
var textarea = document.getElementById("post-content");
var selection = (textarea.value).substring(textarea.selectionStart, textarea.selectionEnd);