jquery focus, but with more accurate postion - javascript

you can easily find focus() answers from the site or any site.. but what i want to know, how can i use focus after what i just inserted inside the input box.
$("input").val('#user').focus(); // this goes to start of the input box and foucs from start, but i want it to focus after the #user
$("input").val('#user today i did new things').focus(5); // i added 5 in focus method, obviously its not supported yet!, but the idea behind is, to focus it after #user from complete word.
EDITED:
i just saw that on firefox it works fine, but in chrome it starts the cursor from start. any solution?

Take a look at this question: jQuery Set Cursor Position in Text Area

You can focus an input area by triggering it on change event:
$("input").change(function(){
$(this).focus();
});
and if you want to check how many characters typed you can make a control on its callback:
//will focus if typed text's length is greater than 5
$("input").change(function(){
if($(this).val().length > 5){
$(this).focus();
}
});
hope it helps, Sinan.

Related

How to detect where in an input element user has clicked

Is there a way to detect where in an input element's content a user has clicked? Specifically in Firefox?
I need to know not where the caret is but where the caret would be when the user clicks into an input element.
I am trying to fix a bug in firefox where the user cannot click to place the caret into an input element which has had '.select()' called on it -- the caret fails to appear in firefox, so I want to place it manually if possible.
Thanks!
You can get the pixel position of the user's click (relative to the input field) by reading the click event's offsetX and offsetY:
// get the click position:
document.getElementById('test').onclick = function(e) {
console.log(e.offsetX, e.offsetY)
};
// for testing the 'select' issue:
document.getElementById('btn').onclick = function() {
document.getElementById('test').select();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="test">xxxxxx</textarea>
<button id="btn">Select</button>
Converting that to the desired caret location is not easy, though, because it will depend on font sizes and the text content of the input field. The best I can think of would be to do something like the technique used in textarea-caret-position, except iterating through every possible caret position in the textarea to find the one closest to where the user clicked. Which is almost certainly overkill for the task you have in mind.
(For what it's worth, the current version of firefox (v57) does not seem to have any trouble placing the caret correctly whether the input field is selected or not. I'm not certain whether this was the case in previous versions.)
Found the root of the problem, some bad css had set text-select to auto on input elements. Changing it to text-select:text allowed the fix I used for Safari to work in Firefox as well.

Blur event not firing on <label> - can't find workaround for dealing with hide-on-blur <input> text field

TL;DR how can I get this self-explanatory JSFiddle to work?
From the W3C:
The blur event occurs when an element loses focus either via the pointing device or by tabbing navigation. This event is valid for the following elements: LABEL, INPUT, SELECT, TEXTAREA, and BUTTON.
The basic idea, HTML:
<form>
<label>
<input type="text" />
after focusing in input, there should be no blur when clicking here
</label>
</form>
but blur should fire when clicking here
And JS:
$("form, label").on("blur", function() {
alert("you're not going to see this");
});
It doesn't work. A more illustrative example is in this JSFiddle.
I also tried focusout, with this JSFiddle, but (presumably because it bubbles up from the input), it always fires.
I could probably rig up what I need with a hack like this: https://stackoverflow.com/a/5049387/458614 but I'd rather not have to.
Edit: There are lots of related questions and I have read all that I could find, none of which help. Some talk about setting tabindex=0 on the form or label elements. I have tried this in various permutations but it doesn't help. JSFiddle here. If you put it on the form, blur events do fire when you click outside the form. However, it doesn't apply to any of it's children: it won't pick up anything if you click on the input and then outside the form.
Edit 2: I don't really understand some of the answers posted so far and none seem to really... work. Anyway, to clarify, here is what I am trying to accomplish:
In my app, you can add tags to documents. When you click the "add tag" button, a previously-hidden text input field pops up and is focused. And then...
Clicking outside (on blur) should close the text input field again
Pressing enter should add the tag and close the input field
Clicking the "add tag" button should also add the tag and close the input field
The problem is that #1 and #3 are incompatible. The "add tag" button needs to perform a different action based on whether the text field is open or closed, but because I can only achieve #1 with an onblur event on the text field, the text field is closed by the time any action happens on the "add tag" button for #3.
Here is a JSFiddle with my best attempt so far.
The thing I think you are looking for is
e.stopPropagation();
This Fiddle here shows a little different way to handle it ... it put the hide on a window click (which would blur the input anyways) except on the label, which it would allow the click event to stop inside the label.
Happy coding!
use the below code to achieve the desired
$(document).on("blur", "label",function() {
$("div").append("form or label blurred<br>");
});
Here is the demo Fiddle
Try this it should work
.focus {
border-color:red;
}
$(document).ready(function() {
$('input').blur(function(){
$('input').removeClass("focus");
})
.focus(function() {
$(this).addClass("focus")
});
});
Add this piece of js in your Fiddle. you added listener for label but blur happens on anchor tag.
$("form a").on("blur", function() {
$("div").append("form or label blurred<br>");
});
according to your explanation i have create a demo
$("form > label >a").on("blur", function() {
return false
});
$("#outsideform > a").on("blur", function() {
alert("but blur should fire when clicking here");
});
Check the Demo here
For a while, I am posting an intermediate development. But this definitely will help you where exactly you should look for. The jquery implementation but not your javascript.
This is the real concern.
I have added 3 lines at different places. no big changes.
Added an || $("input").css("visibility") == "visible" to the if
condition
Added $("input").css("visibility","hidden"); to the inner else condition
$("input").css("visibility","visible"); to the outer (and last) else condition.
Please note this is intermediate, you need to click twice after a submit of non-empty text.
If I get time, I would post the correct working thing.
This is the fiddle.
tobek, your JSFiddle with my best attempt so far is almost there. The problem is your selector at the bottom in this section of code:
$("input").on("blur", function(){
$("input").hide();
});
You stated the problem correctly in your comments when you said: "THE PROBLEM: we never get in here because it's already been hidden because the input blurred".
Change the above section to this and I think you'll have what you're looking for.
$("input-blur label").on("blur", function(){
$("input").hide();
});
Because the "Add tag" link is inside the label clicking it doesn't trigger your "blur" function.

IE-10 Cursor position when set focus on textbox using jquery

I have a problem in IE -10(window -7 SP-1) when set focus on a text box. my cursor position at the beginning in text-box. how can i set position End of text-box value.
DEMO
I am try j-query code for this problem --
var input = $("#txt1"); // textbox Id
var len = input.val().length;
input[0].focus();
input[0].setSelectionRange(len, len);
TRY WITH JQUERY CODE
WITH JQUERY problem is resolved but why cursor set beginning in IE-10(window -7 SP-1)?
And any any other solution for this.
This appears to be an implementation choice on the part of the browser. I can't find anywhere in the HTML spec where it says where the cursor should be positioned when a text input gains focus. If you use the mouse to give an input focus, the cursor is at the clicked position in IE10, Firefox and Chrome, but absent a click event, the browsers seem to do their own thing - Chrome, for example, appears to select the entire contents of the input.

How can I continually detect if the focus is set? (Javascript, jQuery)

I'm very new to Javascript (and jQuery). My JSFiddle really shows the issue in the best way possible. http://jsfiddle.net/mkLsr/3/
I'm trying to make it so a search box text input that is focused upon page load, so a user can type into it without clicking into it. However, I also want default text in it that will disappear when the user clicks into the text input and re-appears if they click out of the text field without writing anything.
The problem is that I have other text inputs on the page, and as it is running now, if a user clicks onto one and begins typing, the focus jumps to the originally focused text input. How can I stop this from happening?
I tried using if ($('input:focus').size() == 0) to make it so it would only set the focus if no other focus has been set. Does it not work because it doesn't re-check after the page loads? How can I get it to re-check, or is there some other problem?
I think that a search box that you can automatically type into, that has a default text that is erased upon typing, is about as user friendly as you can get - but I'm really hoping to do it without expense to other input's user-friendliness.
Any help would be appreciated!
* EDIT *
Kai really helped me out with his Javascript solution and use of the "placeholder" HTML attribute. (http://jsfiddle.net/wgwTC/4/).
I'm just curious if someone knows how to apply it cross-browser so that the first text input is in focus still, but the placeholder text is there upon loading the page. Currently it works in Chrome, but not IE (I'm using 9) or Firefox (5.0). If there's a cross-browser solution, it may help others who want the same or similar functionality on future projects.
Here's a solution that uses the placeholder attribute but will fallback to JS for IE <= 9: (See http://jsfiddle.net/wgwTC/2/ for working example):
// Focus on this box by default
$('#header-search-box').focus();
// Support placeholder text for IE <= 9 (which doesn't support placeholder attribute)
if ( $.browser.msie && (parseInt($.browser.version, 10) <= 9) ) {
$('input[name=search]').attr('value', 'Search New Equipment...');
// Set placeholder text on blur
$('input[name=search]').on('blur', function (e) {
if (!e.currentTarget.value.length) {
e.currentTarget.value = 'Search New Equipment...';
}
});
// Clear placeholder text on focus
$('input[name=search]').on('focus', function (e) {
if (e.currentTarget.value === 'Search New Equipment...') {
e.currentTarget.value = '';
}
});
}
I think this does what you're asking (assuming I understand you correctly).
Here's the fiddle: http://jsfiddle.net/jVvX3/2/

jQuery bug in IE when selecting Jeditable select boxes

I'm making an intranet application and experimenting with the Jeditable plugin for jQuery. The following function makes an element (in this case a td element) clickable, which then turns it editable (again in this case selectable, as it's a select box) and checks a key listener to see if tab or shift-tab has been pressed to activate the next or previous editable area.
$('.editBool').editable(function(value, settings){
// show and hide clickable links. shouldn't be important to problem,
// but i don't know at this point
$(this).parent().find('a.editbutton').hide();
$(this).parent().find('a.savebutton').show();
$(this).parent().addClass('notSaved');
// sets a warning if they leave the page without saving edited data
window.onbeforeunload = savePage;
// needed for editable to work (apparently).
return(value);
}, {
data : "{'Yes':'Yes','No':'No'}",
type : 'select',
onblur : 'submit',
callback : function(value, settings) {
// kp is the keypress, sp is a bool checking for the shift key
if (kp == 9){if (sp){$(this).prev().click();}else{$(this).next().click();}kp = null;}
}
});
If I tab through the Jeditable boxes with code like this, I have no problems, until I move the mouse in Internet Explorer (7 and 8). If the currently selected element is a select box (using the code above), when the mouse moves, the select box loses focus and triggers the onblur event. If the mouse doesn't move, focus stays with the select box.
If I use the cursors to try to select another value, focus is lost as well, and again the onblur event is triggered.
This does not happen with any other kind of element I've set as Jeditable (textarea, autogrow textarea, masked text), just on selects, and only in IE 7-8 (maybe 6 as well, but I don't care about 6 anymore). It works as I expect it to work in FF3, Chrome 4+, Opera 10 (focus stays on select box when mouse moves and options can be selected by keyboard arrow commands).
Does anyone have any ideas about why this might be happening?
Thanks.
Clarification time: This bug only happens when using a next() function to go from a jeditable enabled td set to change to text, textedit or autogrow on click, to a jeditable enabled td set to a select box. It doesn't happen when going from text to text, or select to text.
More detail time: The bug is happening when the focus() is called in the jeditable jQuery plugin, line 253:
$(':input:visible:enabled:first', form).focus();
It seems if the mouse is moved after this line, it causes the select box to lose focus. This is driving me nuts, and as I want to solve this one, I've been attacking it every which way I can. I came across a curious oddity by swapping the previous line for this one:
setTimeout(function() { $(':input:visible:enabled:first', form).focus();}, 1000);
During the second between the select box being created and the focus set, if the mouse moves, focus is not lost once set. If the mouse does not move before focus is set, when it does move, focus is lost. This appears to be total fruit and nuttiness. I've been googleing the hell out of this issue, and can't find a solution. Any help would be very much appreciated.
Thanks,

Categories