Left align text input onblur (IE 8 & 9) - javascript

I am looking for a method to left align the contents of a text input box when the user fires the onblur event. I have seen mention of solving the issue with onblur="this.value = this.value", but this does not work in IE.
To Clarify: This issue occurs in Internet Explorer when the user types beyond the width of the textbox and then leaves focus. In Chrome and Firefox, the text will automatically left align, but this does not happen in IE.
Due to request, I've attached code (View in IE):
<input type="text" />
http://jsfiddle.net/t3hjonneh/FZJjW/
Text Field:
After Typing:
After Blur:
How it should look:

This is rather a hack than a proper solution, but somehow it works:
function blurred(elem) {
var range;
// IE only, probably not the best check since it will run in other browsers
// if they ever implement this feature
if (elem.createTextRange) {
range = elem.createTextRange();
range.collapse(true);
range.select();
}
}
<input type="text" onchange="blurred(this);" />
Notice the use of onchange instead of onblur. This is since select() causes some troubles when using onblur.

Here is a jQuery version I mocked up that works in all the major browsers:
$(document).ready(function(){
$('input[type=text]').change(function(){
try{//select nothing but side-effect is that text left justifies
if(/webkit/.test(navigator.userAgent.toLowerCase())){
return;//webkit browsers do it automatically
} else if(this.createTextRange) { //ie
var r = this.createTextRange();
r.collapse(true);
r.select();
} else if(typeof this.selectionStart !== "undefined") { //firefox
this.selectionStart = 0;
this.selectionEnd = 0;
}
} catch(err) {
//?? nobody cares ??
}
});
});

I'd just set a class on that field and then fire up a function with the onBlur in your html: e.g. onBlur="left()" Then in your javascript you can then simply change the class with .setAttribute As an added bonus you can also set other properties for that class as well.
Although I do support the notion of posting relevant code

Related

Is it possible to get selectionchange-like events for an input box in Firefox?

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.

IE9 input setSelectionRange() after paste not working

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.

JavaScript event onblur is firing before onfocus in Firefox

I am getting a problem when using onblur and onfocus event of textbox in Firefox.
In Opera. it works as expected (e.g. onfocus is called first, then onblur).
In Firefox, onblur is called first, then it calls onfocus. This should not happen.
How can this be fixed?
It's good to know that some browsers are broken in this way. Consider the following code.
<input type="text" id="t1" onfocus="is_editing=true" onblur="is_editing=false" />
<input type="text" id="t2" onfocus="is_editing=true" onblur="is_editing=false" />
In Opera, if you click on either textfield, is_editing will be true. If you then tab to the other textfield... is_editing will be false!
The same happens if you replace the above variable assignments with function calls: enableEditing() and disableEditing(), for example: you tab from one field to another, and editing becomes disabled. That is clearly not what people would want!
To avoid this, most browsers now support document.activeElement, which you need to use to do something really nasty like so:
function enableEdit() { is_editing = true; }
/* Can't just unset is_editing here, since broken browsers may
call onblur /after/ onfocus when tabbing between two text elements.
So, we only unset if we don't have a text element focused */
function disableEdit() {
if (!document.activeElement) {
/* For old & broken browser support, could traverse every DOM elem to set
elem.onfocus = function(){ document.activeElement = elem; }
For the meantime, I just assume they aren't broken. */
is_editing = false;
}
// If not focused on a text input type, then it's OK to unset.
else if ("text" != document.activeElement.type) {
is_editing = false;
}
}
Obviously, replace the is_editing assignments with whatever you wanted to happen onblur/onfocus.
With jQuery, you can also apparently use $("*:focus") in the same way as I used document.activeElement above.

Detecting drag drop to HTML textbox?

I have a normal search box on my webpage. It is filled with text: Search this website
This text is removed when you click into the box to type your search query:
onfocus="if(this.value=='Search this website') { this.value=''};
But how can I detect when someone drags text from the page onto the search box, as I often do myself? onfocus is not triggered and the previous text remains.
You need to use the ondrop event, which will only fire if the ondragenter and ondragover events are cancelled. Turns out it's a bit trickier than that because the behavior is different in Firefox than IE, Safari and Chrome.
(function () {
var inp = document.getElementById("test"),
chg = false;
inp.ondragover = inp.ondragenter = function () {
chg = inp.value == "Drop here";
return false;
}
inp.ondrop = function (evt) {
evt = evt || event;
if (chg) {
this.value = evt.dataTransfer.getData("text")
|| evt.dataTransfer.getData("text/plain");
return false;
}
}
})();
Example - Firefox 3+, IE5+, Chrome and Safari. Near as I can tell, Opera doesn't support the event. At least you can get it working for 95% of your visitors though.
Drag Operations - MDC
Have you tried to use the onchange event?
BTW, there is a nifty little jQuery plugin called jquery-defaultvalue which handles all the corner cases for you. If you're using jQuery anyway, it's worth a look.
See - http://www.simplecoding.org/drag-drop-s-ispolzovaniem-html5.html , but page on the russian language (Google Translate would help).

focus doesn't work in IE

i have the following function
function change()
{
var input = document.getElementById('pas');
var input2 = input.cloneNode(false);
input2.type = 'password';
input.parentNode.replaceChild(input2,input);
input2.focus();
}
but focus() doesn't work in ie7, so what can i do!
i want to have the cursor inside of input!
thanks
update
great solution, thanks, but now it doesn't work in opera:(
For IE you need to use a settimeout function due to it being lazy, for example:
setTimeout(function() { document.getElementById('myInput').focus(); }, 10);
From http://www.mkyong.com/javascript/focus-is-not-working-in-ie-solution/
For opera, this may help:
how to set focus in required index on textbox for opera
UPDATE:
The following snippet of code handles the case when the element is unavailable and retries after a short period - perfect for slow loading pages and/or elements not available until some time after.
setTimeout(
function( ) {
var el = document.getElementById( "myInput" ) ;
( el != null ) ? el.focus( ) : setTimeout( arguments.callee , 10 ) ;
}
, 10 ) ;
We hit the same issue. For focusing we are using General function which is applying settimeout solution mentioned in:
http://www.mkyong.com/javascript/focus-is-not-working-in-ie-solution/
with 100 milliseconds.
Still on some screens it's not working properly. Especially when iframes are included.
There is another known and similar IE issue:
IE 9 and IE 10 cannot enter text into input text boxes from time to time ->
IE 9 and IE 10 cannot enter text into input text boxes from time to time
What I have noticed is when you have focus, without pointer, you can apply workaround by pressing TAB key (focus on next element) and than SHIFT+TAB which will return to our target element with focus and typing pointer.
In order to be sure we can type inside input we focus on random element and then on our target input.
$('body').focus();
n.focus();
So we applied the same solution in javascript/JQuery in our general focus function.
So there is an if statement
...
if($.browser.msie) {
setTimeout(function() { try {
$('body').focus(); //First focus on random element
$(n).focus(); //Now focus on target element
} catch (e) { /*just ignore */ } }, 100); //See http://www.mkyong.com/javascript/focus-is-not-working-in-ie-solution/
} else { //Standard FF, Chrome, Safari solution...
...
To be sure since there is big regression we are still keeping solution with settimeout as a backup.
Tested on IE10, IE11, Firefox 45, Chrome 49.0.2623.87
IE7 does not support the focus() method. I don't see any method.
I've had the same issue and was able to get IE to work using code behind by making a SetInitialFocus function and calling it in my PageLoad function.
Take a look at the following example and give it a shot, it worked for me.
http://www.cambiaresearch.com/c4/df9f071c-a9eb-4d82-87fc-1a66bdcc068e/Set-Initial-Focus-on-an-aspnet-Page.aspx
function change() {
var input = document.getElementById('pas');
var input2 = input.cloneNode(false);
input2.type = 'password';
input.parentNode.replaceChild(input2, input);
setTimeout(function () {
input2.focus();
}, 10);
}
In Case you are looking to set focus in 1st input element of last row in table.Name of my div where i have kept my table is tableDiv and i am setting focus to last row's 1st inputtext
setTimeout(function(){
$($('#tableDiv tr:last').find('input[type=text]')[0]).focus();
},2);
#Bojan Tadic THANK YOU!
Below Code did the trick :)
$('body').focus(); //First focus on random element
I think the issue comes up when you use input and a placeholder. Managed so solved this thanks to this answer, I was missing that $(body).focus. Made this code to run only on IE so that all my inputs can be freely accessed by 'tabbing'. Previously when I had only tabIndex on my inputs I was able to move to the next one but focus wasn't complete and couldn't write anything in it.
This is complete code.
$('input[name^="someName"]').on('keydown', function(e){
var keyCode = e.which || e.keyCode;
if(keyCode === 9){
e.preventDefault();
$('body').focus();
var nextTabIndex = parseInt($(this).attr("tabIndex"));
nextTabIndex++;
setTimeout(function(){$('input[tabIndex=' + nextTabIndex +']')[0].focus();},20);
}
});
Its is very easy using jQuery, not sure why you are doing it the hard way :)
In this example I have a class assigned to the input field I want the initial focus set called initFocus. You can use any selector you want to find your element. from your code I would use $("#pas").focus();
$(".initFocus").focus();

Categories

Resources