Maintain focus on an input tag - javascript

I'm trying to keep focus on an input element with this code:
<input onblur="this.focus()" />
But it doesn't seem to work.

If we just call .focus() right on blur event, it will restore focus, but actually there will be no text cursor. To handle this we have to let element to lose focus and then return it in few milliseconds. We can use setTimeout() for this.
$('#inp').on('blur',function () {
var blurEl = $(this);
setTimeout(function() {
blurEl.focus()
}, 10);
});
Here's working example. Be careful - you can't leave text field after you enter it =)
EDIT I used jQuery, but it can be easily done without it.
EDIT2 Here's pure JS version fiddle
<input type="text" id="elemID" />
<script type="text/javascript">
document.getElementById('elemID').onblur = function (event) {
var blurEl = this;
setTimeout(function() {
blurEl.focus()
}, 10);
};
</script>

Related

How do I detect when a div has lost focus?

Given the following markup, I want to detect when an editor has lost focus:
<div class="editor">
<input type="text"/>
<input type="text"/>
</div>
<div class="editor">
<input type="text"/>
<input type="text"/>
</div>
<button>GO</button>
EDIT: As the user tabs through the input elements and as each editor div loses focus (meaning they tabbed outside the div) add the loading class to the div that lost focus.
This bit of jquery is what I expected to work, but it does nothing:
$(".editor")
.blur(function(){
$(this).addClass("loading");
});
This seems to work, until you add the console log and realize it is triggering on every focusout of the inputs.
$('div.editor input').focus( function() {
$(this).parent()
.addClass("focused")
.focusout(function() {
console.log('focusout');
$(this).removeClass("focused")
.addClass("loading");
});
});
Here is a jsfiddle of my test case that I have been working on. I know I am missing something fundamental here. Can some one enlighten me?
EDIT: After some of the comments below, I have this almost working the way I want it. The problem now is detecting when focus changes to somewhere outside an editor div. Here is my current implementation:
function loadData() {
console.log('loading data for editor ' + $(this).attr('id'));
var $editor = $(this).removeClass('loaded')
.addClass('loading');
$.post('/echo/json/', {
delay: 2
})
.done(function () {
$editor.removeClass('loading')
.addClass('loaded');
});
}
$('div.editor input').on('focusin', function () {
console.log('focus changed');
$editor = $(this).closest('.editor');
console.log('current editor is ' + $editor.attr('id'));
if (!$editor.hasClass('focused')) {
console.log('switched editors');
$('.editor.focused')
.removeClass('focused')
.each(loadData);
$editor.addClass('focused');
}
})
A bit more complicated, and using classes for state. I have also added in the next bit of complexity which is to make an async call out when an editor loses focus. Here a my jsfiddle of my current work.
If you wish to treat entry and exit of the pairs of inputs as if they were combined into a single control, you need to see if the element gaining focus is in the same editor. You can do this be delaying the check by one cycle using a setTimeout of 0 (which waits until all current tasks have completed).
$('div.editor input').focusout(function () {
var $editor = $(this).closest('.editor');
// wait for the new element to be focused
setTimeout(function () {
// See if the new focused element is in the editor
if ($.contains($editor[0], document.activeElement)) {
$editor.addClass("focused").removeClass("loading");
}
else
{
$editor.removeClass("focused").addClass("loading");
}
}, 1);
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/8s8ayv52/18/
To complete the puzzle (get your initial green state) you will also need to also catch the focusin event and see if it is coming from the same editor or not (save the previous focused element in a global etc).
Side note: I recently had to write a jQuery plugin that did all this for groups of elements. It generates custom groupfocus and groupblur events to make the rest of the code easier to work with.
Update 1: http://jsfiddle.net/TrueBlueAussie/0y2dvxpf/4/
Based on your new example, you can catch the focusin repeatedly without damage, so tracking the previous focus is not necessary after all. Using my previous setTimeout example resolves the problem you have with clicking outside the divs.
$('div.editor input').focusin(function(){
var $editor = $(this).closest('.editor');
$editor.addClass("focused").removeClass("loading");
}).focusout(function () {
var $editor = $(this).closest('.editor');
// wait for the new element to be focused
setTimeout(function () {
// See if the new focused element is in the editor
if (!$.contains($editor[0], document.activeElement)) {
$editor.removeClass("focused").each(loadData);
}
}, 0);
});
Here's what worked for me:
$(".editor").on("focusout", function() {
var $this = $(this);
setTimeout(function() {
$this.toggleClass("loading", !($this.find(":focus").length));
}, 0);
});
Example:
http://jsfiddle.net/Meligy/Lxm6720k/
I think you can do this. this is an exemple I did. Check it out:
http://jsfiddle.net/igoralves1/j9soL21x/
$( "#divTest" ).focusout(function() {
alert("focusout");
});

Jquery on Input not working on dynamically inserted value

I'm trying to alert a value using jquery when it is generated from a javascript code, the value is generated on the input box the problem is jquery cannot detect the changes, commands i tested are "change, input" but when i manually input a value jquery triggers
sample code:
value is dynamically generated on the javascript and pushed / inserted to the inputbox, the value is not manually generated
javascript:
document.getElementById("displayDID").value = DisplayName ;
html:
<input type="text" id="displayDID" />
jquery:
$('#displayDID').on("input" ,function() {
var work = $(this).val();
alert(work);
});
the value of the id="displayDID" changes but jquery cannot detect it after execution.
sample fiddle http://jsfiddle.net/SU7bU/1/
add trigger to it
$('#gen').on('click',function() {
$('#field').val('val').trigger("change");
});
$(document).on("change",'#field' ,function() {
var work = $(this).val();
alert(work);
});
http://jsfiddle.net/ytexj/
It is because you have added the script before input is ready.Due to which, event is not getting set on that element.write the code on document ready:
$(document).ready(function(){
$('#displayDID').on("input" ,function() {
var work = $(this).val();
alert(work);
});
})
or use event delegation:
$(document).on("input",'#displayDID' ,function() {
var work = $(this).val();
alert(work);
});
Ok I will propose you one answer and let's see if it solve your problem.
If you use keyup, and you insert 3350 value, you will display 4 alert, and I think you want to display only 1 alert.
$(document).ready(function() {
var interval;
$("#variazioneAnticipo").on("input", function() {
var variazioneAnticipo = $("#variazioneAnticipo").val();
clearInterval(interval);
interval = setTimeout(function(){ showValue(variazioneAnticipo) }, 1000);
});
});
function showValue(value) {
alert("ANTICIPO VARIATO: " + value);
}
<input id="variazioneAnticipo" class="rightAlligned form-control" style="width: 60%" type="number" step="0.01" min="0" value="3" />
I explain it, when you input anything into the input, will trigger a setTimeout in 1 sec, if you press another key under this time, we clear the timeOut and we triiger again, so you will only have 1 alert 1 sec after the last input insert.
I hope it helps you, and soyy for my english :D

JQuery advice or suggestion for new alternative solution

Is there a better way of doing this
$("#<%=Text_Name.ClientID%>").mouseleave(function () {
var t_name = this.value;
if (t_name == "") {
$(this).val("Name");
$("#<%=Text_Name.ClientID%>").addClass("grey_add");
$("#<%=Text_Name.ClientID%>").removeClass("black_add");
}
});
What this code does is when you scroll out of the textbox it leaves the it returns to you "Name".
A con about using this technique is when user move mouse out the textbox it fills something in when user types.
It's really simple with jQuery, check this:
html
<input type="text" id="myInput" value="Name" />
jQuery
$(function() {
$('#myInput').focusin(function() {
$(this).val('');
});
$('#myInput').focusout(function() {
$(this).val('Name');
$(this).css('background-color', '#ccc');
});
});
Here goes jsFiddle.
No need for plugins or much code for this.
<input name="search" placeholder="<%=Text_Name.ClientID%>"/>
no javascript needed.
$("#<%=Text_Name.ClientID%>").blur(function () {
var t_name = this.value;
if (t_name == "") {
$(this).val("Name");
$("#<%=Text_Name.ClientID%>").addClass("grey_add");
$("#<%=Text_Name.ClientID%>").removeClass("black_add");
}
});
This event happens when you focus on something else, which is what the textbox at the top right of stack overflow probably uses.
You could look into the watermark plugin I was posting about here:
Custom jQuery plugin return val()
Just edit it to be mouseover / mouseout instead of on focus/blur.
jsFiddle edited to show mouseover/mouseout

Simulate an "ontype" event

I want to simulate the Google Search effect that even with the search box not focused, the user can start typing and the input box will capture all keyboard strokes.
I have looked for an ontype event, but haven't found anything. I know that the event object in callbacks for events like click has keyboard information, but I don't think this is what I'm after.
This does the job:
$(document).on('keydown', function() {
$('input').focus();
});
HTML:
<input type="text" id="txtSearch" />
Javascript:
var googleLikeKeyCapture = {
inputField : null,
documentKeydown: function(event) {
var inputField = googleLikeKeyCapture.inputField;
if(event.target != inputField.get(0)) {
event.target = inputField.get(0);
inputField.focus();
}
},
init: function() {
googleLikeKeyCapture.inputField = $('#txtSearch');
$(document).bind('keydown', googleLikeKeyCapture.documentKeydown);
googleLikeKeyCapture.inputField
.focus(function() {
$(document).unbind('keydown');
})
.blur(function() {
$(document).bind('keydown', googleLikeKeyCapture.documentKeydown);
});
googleLikeKeyCapture.init = function() {};
}
};
$(googleLikeKeyCapture.init);
Also you can find jsFiddle example here
EDIT :
And now it's a jQuery plugin. :) If keydown occures in a textarea or input field it doesn't capture keys, anything else goes to designated input field. If your selector matches more than one element it only uses the first element.
Usage: $('#txtSearch').captureKeys();
The event you are after is onkeypress.
Try this jQuery Text Change Event plugin:
http://www.zurb.com/playground/jquery-text-change-custom-event

Detect which form input has focus using JavaScript or jQuery

How do you detect which form input has focus using JavaScript or jQuery?
From within a function I want to be able to determine which form input has focus. I'd like to be able to do this in straight JavaScript and/or jQuery.
document.activeElement, it's been supported in IE for a long time and the latest versions of FF and chrome support it also. If nothing has focus, it returns the document.body object.
I am not sure if this is the most efficient way, but you could try:
var selectedInput = null;
$(function() {
$('input, textarea, select').focus(function() {
selectedInput = this;
}).blur(function(){
selectedInput = null;
});
});
If all you want to do is change the CSS for a particular form field when it gets focus, you could use the CSS ":focus" selector. For compatibility with IE6 which doesn't support this, you could use the IE7 library.
Otherwise, you could use the onfocus and onblur events.
something like:
<input type="text" onfocus="txtfocus=1" onblur="txtfocus=0" />
and then have something like this in your javascript
if (txtfocus==1)
{
//Whatever code you want to run
}
if (txtfocus==0)
{
//Something else here
}
But that would just be my way of doing it, and it might not be extremely practical if you have, say 10 inputs :)
I would do it this way: I used a function that would return a 1 if the ID of the element it was sent was one that would trigger my event, and all others would return a 0, and the "if" statement would then just fall-through and not do anything:
function getSender(field) {
switch (field.id) {
case "someID":
case "someOtherID":
return 1;
break;
default:
return 0;
}
}
function doSomething(elem) {
if (getSender(elem) == 1) {
// do your stuff
}
/* else {
// do something else
} */
}
HTML Markup:
<input id="someID" onfocus="doSomething(this)" />
<input id="someOtherID" onfocus="doSomething(this)" />
<input id="someOtherGodForsakenID" onfocus="doSomething(this)" />
The first two will do the event in doSomething, the last one won't (or will do the else clause if uncommented).
-Tom
Here's a solution for text/password/textarea (not sure if I forgot others that can get focus, but they could be easily added by modifying the if clauses... an improvement could be made on the design by putting the if's body in it's own function to determine suitable inputs that can get focus).
Assuming that you can rely on the user sporting a browser that is not pre-historic (http://www.caniuse.com/#feat=dataset):
<script>
//The selector to get the text/password/textarea input that has focus is: jQuery('[data-selected=true]')
jQuery(document).ready(function() {
jQuery('body').bind({'focusin': function(Event){
var Target = jQuery(Event.target);
if(Target.is(':text')||Target.is(':password')||Target.is('textarea'))
{
Target.attr('data-selected', 'true');
}
}, 'focusout': function(Event){
var Target = jQuery(Event.target);
if(Target.is(':text')||Target.is(':password')||Target.is('textarea'))
{
Target.attr('data-selected', 'false');
}
}});
});
</script>
For pre-historic browsers, you can use the uglier:
<script>
//The selector to get the text/password/textarea input that has focus is: jQuery('[name='+jQuery('body').data('Selected_input')+']')
jQuery(document).ready(function() {
jQuery('body').bind({'focusin': function(Event){
var Target = jQuery(Event.target);
if(Target.is(':text')||Target.is(':password')||target.is('textarea'))
{
jQuery('body').data('Selected_input', Target.attr('name'));
}
}, 'focusout': function(Event){
var Target = jQuery(Event.target);
if(Target.is(':text')||Target.is(':password')||target.is('textarea'))
{
jQuery('body').data('Selected_input', null);
}
}});
});
</script>
You only need one listener if you use event bubbling (and bind it to the document); one per form is reasonable, though:
var selectedInput = null;
$(function() {
$('form').on('focus', 'input, textarea, select', function() {
selectedInput = this;
}).on('blur', 'input, textarea, select', function() {
selectedInput = null;
});
});
(Maybe you should move the selectedInput variable to the form.)
You can use this
<input type="text" onfocus="myFunction()">
It triggers the function when the input is focused.
Try
window.getSelection().getRangeAt(0).startContainer

Categories