I'm trying to create a html/javascript keyboard which will fill an input
The problem is that when the user selects in the middle of input and clicks any keyboard button the character will be added to the end of the input.
<input type="text" id="input"/>
<button onclick="document.getElementById('input').value+=this.innerHTML;document.getElementById('input').focus()">A</button>
<button onclick="document.getElementById('input').value+=this.innerHTML;document.getElementById('input').focus()">B</button>
<button onclick="document.getElementById('input').value+=this.innerHTML;document.getElementById('input').focus()">C</button>
Any solution
Jsfiddle here
Full example (missing some numbers etc..)
can point whereveryou want.. and it stays there.
Creates the keyboard dynamically,only one eventlistener
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>keyboard</title>
<style>
body>div{
clear:both;
overflow:auto;
border:2px solid grey;
}
body>div>div{
width:64px;line-height:64px;float:left;
border:1px solid grey;
text-align:center;
}
</style>
<script>
(function(W){
var D,K,I,pos=0;
function init(){
D=W.document;
I=document.createElement('input');
document.body.appendChild(I);
K=D.createElement('div');
K.id="k";
K.addEventListener('click',h,false);
var L='a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z'.split(','),
l=L.length;
for(var a=0;a<l;a++){
K.appendChild(document.createElement('div')).innerText=L[a];
}
document.body.appendChild(K);
}
function h(e){
if(e.target.parentNode.id=='k'){
pos=(I.selectionStart?I.selectionStart:pos?pos:0);
var end=I.selectionEnd?I.selectionEnd:pos;
I.value=I.value.substr(0,pos)+
e.target.innerText+
I.value.substr(end);
I.focus();
pos++
I.selectionStart=pos;
I.selectionEnd=pos;
}
}
W.addEventListener('load',init,false);
})(window)
</script>
</head>
<body>
</body>
</html>
ps.: I tested in Chrome.
EDIT
the only thing that doesnot work is if you select a text and write before deleting it it starts where te selection starts and leaves yor other selected letters where they are.
EDIT 2 everything you expect works
Without correcting any other bad JS practices in the snippet, the correect solution consists of the use of selectionStart.
document.getElementById('input').value =
document.getElementById('input').value.substr(
0, document.getElementById('input').selectionStart) +
this.innerHTML +
document.getElementById('input').value.substr(
document.getElementById('input').selectionStart);
document.getElementById('input').focus();
I updated your JSfiddle to have a working example.
Link
<html>
<head>
<title>Testing</title>
<script type="text/javascript">
var cursorLocation = 0;
function insertValue(buttonClicked) {
var input = document.getElementById('input');
input.value = input.value.substring(0, cursorLocation) + buttonClicked.innerHTML + input.value.substring(cursorLocation);
cursorLocation += 1;
}
// Script found here:
// http://stackoverflow.com/questions/2897155/get-cursor-position-within-an-text-input-field
function doGetCaretPosition(oField) {
// Initialize
var iCaretPos = 0;
// IE Support
if (document.selection) {
// Set focus on the element
oField.focus ();
// To get cursor position, get empty selection range
var oSel = document.selection.createRange ();
// Move selection start to 0 position
oSel.moveStart ('character', -oField.value.length);
// The caret position is selection length
iCaretPos = oSel.text.length;
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0')
iCaretPos = oField.selectionStart;
// Return results
cursorLocation = iCaretPos;
}
</script>
</head>
<body>
<input onblur="doGetCaretPosition(this)" type="text" id="input"/>
<button onclick="insertValue(this)">A</button>
<button onclick="insertValue(this)">B</button>
<button onclick="insertValue(this)">C</button>
</body>
</html>
Related
I have some input type=button which are created dynamically using JavaScript. Here I need to shift those clockwise while click on button. Here is my code:
<!-- Enter your HTML code here -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Buttons Grid</title>
</head>
<body>
<div id="btns" style="width:75%;">
</div>
<script>
for(var i=0;i<9;i++){
var index=i+1;
var element = document.createElement("input");
element.type = "button";
element.value = index;
element.id = "btn"+index;
element.setAttribute("style","width:30%;height:48px;font-size:24px");
var foo = document.getElementById("btns");
//Append the element in page (in span).
foo.appendChild(element);
}
document.getElementById("btn5").onclick=function(){
}
</script>
</body>
</html>
Here I need when user will click one button 5 the buttons present around button5 will move clockwise means button4 will shift to first place without changing its ids.
Something like this?
let container = document.querySelector("#btns");
container.insertBefore(container.lastElementChild, container.firstElementChild);
// or this ?
// container.appendChild(container.firstElementChild);
I suppose you don't need to create the buttons in js. You can create in html code. And just play with innertext of btns. My approach was like this;
btn5.addEventListener('click', () => {
const textofBtn = btn1.innerText;
btn1.innerText = btn4.innerText;
btn4.innerText = btn7.innerText;
btn7.innerText = btn8.innerText;
btn8.innerText = btn9.innerText;
btn9.innerText = btn6.innerText;
btn6.innerText = btn3.innerText;
btn3.innerText = btn2.innerText;
btn2.innerText = textofBtn;
});
but I saw another solution looking like more elegant here is you can check;
let nums=[1,2,3,6,9,8,7,4];
const ids=[1,2,3,6,9,8,7,4];
let btn5=document.getElementById("btn5");
btn5.onclick=function() {
nums.unshift(nums.pop());
for (i=0; i<=7; i++) {
document.getElementById("btn"+ids[i]).innerHTML=nums[i];
}
}
// writed by mark_russellbro1(hackerrank username)
I want to fire an event before cut, so that I can get what text is being cut i.e. what has been already selected. I am currently using the following code, which doesn't seem to work as desired.
$("#editor").bind({
cut:function(){
console.log('Cut Detected');
alert(editor.selection.getRange());
}
});
editor is the id of the "div" tag which is editable. editor.selection.getRange() returns the start and end of selection.
edit I am woring with content editable div and want to apply the functionality on it.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Editor</title>
</head>
<body>
<div id='myTa' contenteditable>hello world where are you</div>
<script type='text/javascript' src='jquery-2.1.4.min.js'></script>
<script type='text/javascript'>
$("#myTa").on("cut", function(){
alert(this.selectionStart+ " to " + this.selectionEnd);
})
</script>
</body>
</html>
You are correct that you need to use the cut event. The ClipboardEvent API is apparently unstable but yes, I would have thought it would include the text being moved onto the clipboard.
The following works for me:
$("textarea").on("cut", function(){
alert(this.value.substring(this.selectionStart, this.selectionEnd));
})
It's worth noting that bind is deprecated in jQuery, you should use on instead. Try out the snippet:
$("textarea").on("cut", function() {
alert(this.value.substring(this.selectionStart, this.selectionEnd));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea></textarea>
I think at first that clipboardEvent will have the clipped text, but it seems not, so I try to find the selection related properties of input and found it.
And the reference is HTMLInputElement.
This codes work in presumption that your $("#editor") is either an input or textarea.
$("#editor").bind({
cut:function(e){
console.log('Cut Detected');
var $this = $(this);
var selectStart = this.selectionStart;
var selectionEnd = this.selectionEnd;
var clippedValue = $this.val().slice(selectStart, selectionEnd);
// Now you have the clipped value, do whatever you want with the
// value.
alert(clippedValue);
}
});
For works on contentediable, you can do this, which I just found info from Return HTML from a user-selected text and MDN
$("#myTa").on("cut", function(e){
// Seems diff bro
var selections = window.getSelection();
var currentSelection = selections.getRangeAt(0);
var start = currentSelection.startOffset;
var end = currentSelection.endOffset;
var selectedContents = currentSelection.toString();
// Do whatever you want.
console.log(start, end);
console.log(selectedContents);
alert(selectedContents);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id='myTa' contenteditable>ask;ndjkasn asdbasj aujs d sdib askjbnsaab asbh mjn a</div>
I have got the solution to my answer. apperently there is an editor.on('cut',function(e)) in ace editor I use
editor.on("cut", function(e){
console.log('Cut Detected');
console.log(editor.selection.getRange());
});
I was able to make the text loop infinitely and the body color change once:
<?php?>
<style type="text/css">
<!--
header{background-color:orange;}
#color1{background-color:red;}
#color2{background-color:green;}
#color3{background-color:blue;}
-->
</style>
<script type="text/javascript">
<!--
var flip = (function() {
var flip = ['_addText1','_addText2','_addText3'];
var count = -1;
return function() {
return flip[++count % flip.length];
}
}());
-->
</script>
<body id="color1">
<header onclick="document.getElementById('click').innerHTML = flip(); document.getElementById('color1').setAttribute('id', 'color2');">
<h1>StaticText<a id="click">_ThisWillChange</a></h1>
<p>Click anywhere in the header to change the text above.<br />
This will also change the body color.</p>
</header>
</body>
<?php?>
The first problem is; if I add more color changes to the 'onclick' attribute it stops working all together. Basically I want the color to loop with the text:
document.getElementById('color2').setAttribute('id', 'color3');
document.getElementById('color3').setAttribute('id', 'color1');
The second problem is that I'm not really 'fluent' in javascript. I'm actually lucky I figured out this much to be honest.
I'm sure there's a way to put it all into the javascript (to keep my HTML clean), but I don't know how.
Any help would be most appreciated! Thanks in advance...
Why do you want to change the id of the element if you are so keen to set the color.
You can just the class on the body element which should get the work done for you.
Secondly it's a bad practice to bind events inline. Use javascript to bind the events as well.
<body id="color1" class="color1">
This is one way of writing the code.
Code
var header = document.getElementsByTagName('header')[0];
header.addEventListener('click', function () {
var body = document.getElementById('color1');
document.getElementById('click').innerHTML = flip("text");
body.className = flip("color");
});
var flip = (function () {
var flip = ['_addText1', '_addText2', '_addText3'],
colors = ["color1", "color2", "color3"];
var count = -1,
colorCount = -1;
return function (arg) {
if(arg === 'text')
return flip[++count % flip.length];
if(arg === 'color')
return colors[++colorCount % colors.length];
}
})();
HTML
<body id="color1" class="color0">
<header>
<h1>StaticText<a id="click">_ThisWillChange</a></h1>
<p>Click anywhere in the header to change the text above.
<br />This will also change the body color.</p>
</header>
</body>
CSS
header {
background-color:orange;
}
.color0 {
background-color:yellow;
}
.color1 {
background-color:red;
}
.color2 {
background-color:green;
}
.color3 {
background-color:blue;
}
Check Fiddle
I use below code to capture mouse coordinate, and bind it to a div(container). and there's one more div called subDiv inside container. I found that no matter where I move inside subDiv, the coordinate is always the one I just entered subDiv (e.g. I enter subDiv at (10,10), no mater where I move in subDiv, the coordinate is always (10,10)).
Anybody know why?
var x,y;
var e = e||window.event;
return {
x:e.clientX+document.body.scrollLeft+document.documentElement.scrollLeft,
y:e.clientY+document.body.scrollTop+document.documentElement.scrollTop
};
What you pasted works as following demos. Check other code.
<!DOCTYPE html>
<html>
<head>
<script>
function test(e){
var x,y;
var e = e||window.event;
return {
x:e.clientX+document.body.scrollLeft+document.documentElement.scrollLeft,
y:e.clientY+document.body.scrollTop+document.documentElement.scrollTop
};
}
function myFunction(event){
var x = test(event);
document.getElementById("demo").innerHTML=x.x + '.' + x.y;
}
</script>
</head>
<body>
<div id="container">
<div id="subDiv" style="width:199px;height:99px;border:1px solid" onmousemove="myFunction(event)"></div>
</div>
<p id="demo"></p>
</body>
</html>
I would like to specify that firefox select a range. I can do this easily with IE, using range.select();. It appears that FFX expects a dom element instead. Am I mistaken, or is there a better way to go about this?
I start by getting the text selection, converting it to a range (I think?) and saving the text selection. This is where I'm getting the range from initially:
// Before modifying selection, save it
var userSelection,selectedText = '';
if(window.getSelection){
userSelection=window.getSelection();
}
else if(document.selection){
userSelection=document.selection.createRange();
}
selectedText=userSelection;
if(userSelection.text){
selectedText=userSelection.text;
}
if(/msie|MSIE/.test(navigator.userAgent) == false){
selectedText=selectedText.toString();
}
origRange = userSelection;
I later change the selection (successfully). I do so by range in IE and by a dom ID in ffx. But after I do that, I want to set back the selection to the original selection.
This works like a charm in IE:
setTimeout(function(){
origRange.select();
},1000);
I would like to do something like this in FFX:
var s = w.getSelection();
setTimeout(function(){
s.removeAllRanges();
s.addRange(origRange);
},1000);
Unfortunately, FFX has not been cooperative and this doesn't work. Any ideas?
The short answer is: IE and other browsers differ in their implementations of selecting text using JavaScript (IE has its proprietary methods). Have a look at Selecting text with JavaScript.
Also, see setSelectionRange at MDC.
EDIT: After making a little test case, the problem becomes clear.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>addRange test</title>
<style>
#trigger { background: lightgreen }
</style>
</head>
<body>
<p id="test">This is some (rather short) text.</p>
<span id="trigger">Trigger testCase().</span>
<script>
var origRange;
var reselectFunc = function () {
var savedRange = origRange;
savedRange.removeAllRanges();
savedRange.addRange(origRange);
};
var testCase = function () {
// Before modifying selection, save it
var userSelection,selectedText = '';
if(window.getSelection){
userSelection=window.getSelection();
}
else if(document.selection){
userSelection=document.selection.createRange();
}
selectedText=userSelection;
if(userSelection.text){
selectedText=userSelection.text;
}
if(/msie|MSIE/.test(navigator.userAgent) === false){
/* you shouldn't do this kind of browser sniffing,
users of Opera and WebKit based browsers
can easily spoof the UA string */
selectedText=selectedText.toString();
}
origRange = userSelection;
window.setTimeout(reselectFunc, 1000);
};
window.onload = function () {
var el = document.getElementById("trigger");
el.onmouseover = testCase;
};
</script>
</body>
</html>
When testing this in Firefox, Chromium and Opera, the debugging tools show that after invoking removeAllRanges in reselectFunc, both savedRange and origRange are reset. Invoking addRange with such an object causes an exception to be thrown in Firefox:
uncaught exception: [Exception...
"Could not convert JavaScript argument
arg 0 [nsISelection.addRange]"
nsresult: "0x80570009
(NS_ERROR_XPC_BAD_CONVERT_JS)"
location: "JS frame ::
file:///home/mk/tests/addrange.html ::
anonymous :: line 19" data: no]
No need to say that in all three browsers no text is selected.
Apparently this in intended behaviour. All variables assigned a (DOM)Selection object are reset after calling removeAllRanges.
Thank you Marcel. You're right, the trick is to clone the range, then remove the specific original range. This way we can revert to the cloned range. Your help led me to the below code, which switches the selection to elsewhere, and then back according to a timeout.
I couldn't have done it without you, and grant you the correct answer for it :D
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>addRange test</title>
<style>
#trigger { background: lightgreen }
</style>
</head>
<body>
<p id="switch">Switch to this text</p>
<p id="test">This is some (rather short) text.</p>
<span id="trigger">Trigger testCase().</span>
<script>
var origRange;
var s = window.getSelection();
var reselectFunc = function () {
s.removeAllRanges();
s.addRange(origRange);
};
var testCase = function () {
// Before modifying selection, save it
var userSelection,selectedText = '';
if(window.getSelection){
userSelection=window.getSelection();
}
else if(document.selection){
userSelection=document.selection.createRange();
}
selectedText=userSelection;
if(userSelection.text){
selectedText=userSelection.text;
}
if(/msie|MSIE/.test(navigator.userAgent) === false){
/* you shouldn't do this kind of browser sniffing,
users of Opera and WebKit based browsers
can easily spoof the UA string */
selectedText=selectedText.toString();
}
origRange = userSelection;
var range = s.getRangeAt(0);
origRange = range.cloneRange();
var sasDom = document.getElementById("switch");
s.removeRange(range);
range.selectNode(sasDom);
s.addRange(range);
window.setTimeout(reselectFunc, 1000);
};
window.onload = function () {
var el = document.getElementById("trigger");
el.onmouseover = testCase;
};
</script>
</body>
</html>