I have to manually set the caret-position to 0 in an input-field (in the input-event). I need to support >= IE9. Even in IE9 this works ok as long as I do normal input (pressing keys on my keyboard). But as soon as I use copy&paste, the caret isn't set to the desired position (0).
Steps to reproduce:
Open IE in IE9-Mode
Open fiddle below
Type into the input-field (works ok, the caret gets set to 0)
Paste something into the input-field (fails, the caret gets set to the end of the pasted text)
Fiddle: https://jsfiddle.net/wv61t7k5/7/
Code
<input type="text" />
document.querySelector('input').addEventListener('input', function(){
this.setSelectionRange(0,0);
});
Funny. First I thought IE9 maybe would not fire the event on pasting, but it does. No idea why this would not work.
However, you could use the keyup event. This is definitely not as good as using input but will work in IE9.
document.querySelector('input').addEventListener('keyup', function(e){
if (e.key != 'Left' && e.key != 'Right' &&
e.key != 'Shift' && e.key != 'Control') {
this.setSelectionRange(0,0);
}
});
To still be able to select text by keyboard, you'd have to exclude some keys.
Here is an updated Fiddle.
Update
Well, this still does not work if the user pastes text by using mouse and context menu. Happily IE knows the paste event. Unhappily there is no after paste event, so you'd end up using a timeout:
document.querySelector('input').addEventListener('input', function(e){
this.setSelectionRange(0,0);
});
document.querySelector('input').addEventListener('paste', function() {
var that = this;
setTimeout(function() {
that.setSelectionRange(0,0);
}, 100);
});
Here is a Fiddle.
Related
I have a button that is enabled or disabled if, respectively, there is or is not text inside an input, as shown in the code snippet below:
var input = document.getElementById('myInput');
var btn = document.getElementById('myButton');
$(input).on('keyup', function(){
if((input.value != null) && (input.value != ''))
$(btn).removeClass('btnDisabled');
else
$(btn).addClass('btnDisabled');
});
Using keyup event it is working good in my aplication on an smarthphone with Android 6.0.1. But for some reason, on an tablet with Android 4.4.2 if backspace key are pressed till the begin of input, erasing all the text value, the button is still enabled.
I researched this problem but I'm still not sure if the WebView version interferes with this. I think so.
I used other code snippets to see if the event is triggered by the "backspace" button, as shown below:
$(input).on('keydown', function(event){ //I tried keyup, keydown and keypress
var key = event.keyCode || event.charCode;
console.log("keydown " + key, "length " + input.value.length);
//if(key == 8 && input.value.length == 1) $(btn).addClass('btnDisabled');
});
With this test I saw that the backspace does not trigger the event and the variable key is always equal to 0.
I need to disable the button when input is empty. Where am I going wrong?
Right now, I thank those who help! :D
There is another event that you can use: input
https://developer.mozilla.org/en-US/docs/Web/Events/input
The DOM input event is fired synchronously when the value of an <input>, <select>, or <textarea> element is changed.
In this case, change
$(input).on('keydown',
to
$(input).on('input',
See also: https://caniuse.com/#search=input
How can I get the selected text inside an input box in Firefox?
This is apparently a fundamental difference in the way that JavaScript works between Chrome and Firefox. To reproduce:
Navigate to www.google.com
Open JS console
Type following line: document.addEventListener("selectionchange", () => console.log(document.getSelection().toString()))
Type "text" into Google search box and do not hit enter
Use the mouse to select different portions of the "text" in the search box
In Chrome, you will see the event raised for selected text within the input element. This is consistent across various web pages that use input fields. In Firefox, the event is raised for selections outside the input, but when the text in the box is selected, no event is raised.
I have not found any explicit reference to this difference in any Mozilla documentation, nor have I found mention of it on any other web page.
Related but different question
Firefox Web Extension “selectionchange” is an older question, and the dom.select_events.enabled config attribute is now defaulted to true in FF 56. There is a second config attribute, dom.select_events.textcontrols.enabled that seems like what I'm looking for, but changing that value to true doesn't seem to have any effect.
Additional info (Edit 1)
Apparently there isn't even a way to get selected text in a textbox in FF? The following code also doesn't work:
setInterval(() => console.log(document.getSelection().toString()), 1000)
In FF, this will never return the selected text in an input field. In Chrome, it will.
Is this just a feature gap in FF? Is there no other way to extract selected text from a form field?
For me, setting dom.select_events.textcontrols.enabled in firefox did not enable document.addEventListener("selectionchange"... events for within textarea changes, but what it enabled was <textarea onselectionchange="...">.
By adding your handler to both, and toggling that firefox flag, you should get something that works in Chrome, Safari, and Edge (through document selectionchange) and in Firefox (through textarea onselectionchange).
I wasn't able to detect document.onselectionchange events from inputs or textareas in Firefox (86), but I am able to detect select events from the textareas themselves (onselect).
(Thanks to this post [in Russian] for the answer)
Based on this answer I have been able to create the following:
window.addEventListener('mouseup', function () {
selection = getSelectedText();
});
function getSelectedText() {
let elem = document.activeElement;
let elemType = elem ? elem.tagName.toLowerCase() : 'none';
if (elemType === 'input' || elemType === 'textarea') {
return elem.value.substr(elem.selectionStart, elem.selectionEnd - elem.selectionStart);
}
if (window.getSelection) {
return window.getSelection().toString();
}
if (document.selection && document.selection.type !== 'Control') {
return document.selection.createRange().text;
}
return '';
}
My testing so far shows that this seems to work well for both Chrome and Firefox.
I would like to switch between pages using arrows (37 - left arrow, 39 - right arrow). The code below works correctly with Firefox, Chrome and Internet Explorer.
The solution does not work with Microsoft Edge after Back (back in browsing history) button has been clicked in the browser. Does anybody know how to fix it?
<script type="text/javascript">
window.addEventListener("keydown", checkKeyPressed, false);
function checkKeyPressed(event) {
var x = event.which || event.keyCode;
if (x == 37) { window.location.href = "page1.html";}
if (x == 39) { window.location.href = "page2.html";}
};
</script>
This looks like a bug. In that when you use the navigation controls (or the refresh button) the window seems to lose focus and so keydown events do not fire. Also window.focus doesn't seem to work as expected either.
But I have found a workaround (or two). The first is to modify your script to look like this:
<script>
window.onload = function(){
document.body.focus();
document.addEventListener("keydown", checkKeyPressed, false);
function checkKeyPressed(event) {
var x = event.which || event.keyCode;
if (x == 37) { window.location.href = "page1.html"; }
if (x == 39) { window.location.href = "page2.html"; }
};
}
</script>
You then need to add a tab index to the body tag e.g:
<body tabindex="1">
This then allows you to programmatically set the focus of the page (And it isn't ignored by Microsoft Edge like window.focus() is) The reason you need to add tabindex to the body is because the focus method is implicitly applicable to a limited set of elements, chiefly form and <a href> tags. In recent browser versions, the event can be extended to include all element types by explicitly setting the element's tabindex property.
This workaround does add a potential accessibility issue since your element can gain focus via keyboard commands, such as the Tab key. Although I'm not sure how much of a problem that really is.
The second option is to add a form element to your page and either manually set focus to it or add the autofocus attribute:
<input autofocus>
Edge seems to respect this and gives the element auto focus and your key down events will now fire. Sadly You can't just hide this element, since if it's hidden it no longer get auto focus. (maybe you could set it's opacity to 0) but I didn't try.
Of the two options I prefer workaround 1. I will file this as a bug with the Edge team on connect when I get a chance this afternoon.
Chrome :
Following code is working in Chrome.
$('.links').click(function(e) {
if(e.which == 2) {
console.log(e.which); // prints 2
//e.preventDefault();
//e.stopPropagation();
return false;
}
});
Firefox :
Since above code doesn't catch middle button / mouse wheel click event in firefox, I tried following which is able to catch mouse wheel click event.
$('.links').mousedown(function(e) {
if(e.which == 2) {
console.log(e.which); // prints 2
//e.preventDefault();
//e.stopPropagation();
return false;
}
});
Above code prints 2. But return false; is not working.
When I replaced console.log with alert then it works. But I can't & don't want to use alerts.
I tried mouseup, mousewheel events also. But it didn't work.
I tried attachEvent also but, I got an error(attchEvent is not a function).
I am using below mentioned js files :
jQuery-1.10.2.min.js
jquery.easyui.min.js
jquery-ui.js
jquery.ui.core.js
You can refer below links for more clarity.
jsfiddle.net/nilamnaik1989/vntLyvd2/3
jsfiddle.net/nilamnaik1989/2Lq6mLdp
http://jsfiddle.net/nilamnaik1989/powjm7qf/
http://jsfiddle.net/nilamnaik1989/q6kLvL1p/
Following are some good links. But anyhow it doesn't solve my problem.
event.preventDefault() vs. return false
event.preventDefault() vs. return false (no jQuery)
http://www.markupjavascript.com/2013/10/event-bubbling-how-to-prevent-it.html
I need your valuable inputs.
All click default actions should be cancelable. That's one of the points of this important event. However, certain browsers have exceptions:
IE 5-8 won't prevent the default on text inputs and textareas.
IE9/10 & Opera incorrectly un-check radio buttons when you click on another radio in the same group. It correctly doesn't check the new radio.
IE 5-8, Firefox, & Opera won't prevent the default on select boxes.
Firefox & Chrome feel that one radio button must be checked. If all are unchecked they’ll check the first one you click on, even if the default is being prevented.
See Events - click, mousedown, mouseup, dblclick for some more information.
I had the same issue with firefox, related with
preventDefault();
Everything was working well in Safari, Chrome, Opera and even in IE9 (not kidding)
But, after a lot of reading, I saw that the site was using and old jquery version (1.10), then updated to the latest one (2.1.4) the action was canceled even in Firefox.
Another thing to consider is that I used a variable named "keyPressed" like:
var keyPressed = event.keyCode || event.which || event.charCode
So it was easy for each browser to recognize the key event.
Hope this help!
I have faced the similar problem in FF on middle click.
The following script fixed me the issue and it works fine in FF as well.
$(document).on('click', $(".content"), function(e) {
if(e.button==1) {
e.preventDefault();
return false;
}
})
Can someone provide a good example to simulate the backspace key on a <INPUT> text field?
I need this for a virtual keyboard done in HTML5 and it only needs to work in Webkit browsers.
Notes:
createEvent/initTextEvent/dispatchEvent with charcode 8 (backspace) is being ignored (that seems to work only for printable characters)
changing manually the value using substr() sort of works, but this way the caret moves to the end of the input field (and I want to be able to delete characters in the middle of the input field, just like when using a normal keyboard).
Alright here you go: http://jsfiddle.net/dan_barzilay/WWAh7/2/
The get caret function is used to know where to delete the character, if you need more explaining comment.
The reset cursor function is used to restore the caret position after the backspacing.
**it's using jquery but you can change it to normal js in secounds
Edit: the below is too complicated to use. According to
https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand,
it's just enough to call document.execCommand("delete");.
Here's my solution using setSelectionRange, which works well on Chrome:
https://github.com/gdh1995/vimium-plus/blob/master/lib/dom_utils.js#L169
simulateBackspace: function(element) {
var start = element.selectionStart, end = element.selectionEnd, event;
if (!element.setRangeText) { return; }
if (start >= end) {
if (start <= 0 || !element.setSelectionRange) { return; }
element.setSelectionRange(start - 1, start);
}
element.setRangeText("");
event = document.createEvent("HTMLEvents");
event.initEvent("input", true, false);
element.dispatchEvent(event);
}
Well, the only shortage is that we can not undo the changes it makes.
Add: I find a method to enable undo & redo:
in Javascript textarea undo redo , the both anwsers work well on Chrome