Javascript to run a function when input focus - javascript

What is the code to run a function, say called "myfunction" when a user clicks within an input box (focus).
I have seen examples in jquery but I cant see how to do it with straight javascript.

use the onfocus attribute
<input type="text" onfocus="someFunc()">
<script>
function someFunc(){
}
</script>

var addEvent = (function(){
/// addEventListener works for all modern browsers
if ( window.addEventListener ) {
/// I'm returning a closure after the choice on which method to use
/// has been made, so as not to waste time doing it for each event added.
return function(elm, eventName, listener, useCapture){
return elm.addEventListener(eventName,listener,useCapture||false);
};
}
/// attachEvent works for Internet Explorer
else if ( window.attachEvent ) {
return function(elm, eventName, listener){
/// IE expects the eventName to be onclick, onfocus, onkeydown (and so on)
/// rather than just click, focus, keydown as the other browsers do.
return elm.attachEvent('on'+eventName,listener);
};
}
})();
Using the above cross browser function you can then do the following (once the dom is fully loaded):
addEvent(document.getElementById('your_input'),'focus',function(e){
var input = e.target || e.srcElement;
alert('this input has gained focus!');
});

document.getElementById("elementId").addEventListener("focus",function(e){
//Do Something here
});

Related

How do I disable ondblclick in IE8?

So, I've already tried the selected answer on this:
How to disable ondblclick in JavaScript?
but it doesn't work, on my end. As per usual, I'm suspecting it has something to do with IE8 (since a lot of my previous problems were related to IE8 issues).
This is how my button looks like, keyBtnEvent is a function that changes the class of the div:
function keyBtnEvent(key, id, event) {
//change class of object with id = 'id'
console.log(event + 'event of keyBtnEvent called');
}
<div id="2Key" class="key"
onmouseup="keyBtnEvent('2','2Key','up')"
onmousedown="keyBtnEvent('2','2Key','down')">
<button>2</button>
</div>
So, how do i disable ondblclick in IE8, without using jquery?
This is the proper IE 8 way to do it:
var key = document.getElementById('2Key')
// Feature detection for DOM Event Standard and IE 8 and less
if(window.addEventListener){
// W3C DOM Event Standard
key.addEventListener("dblclick", function(evt) {
evt.preventDefault(); // stop the event
evt.stopPropagation(); // don't bubble the event
});
} else if(window.attachEvent){
// IE 8 or less
key.attachEvent("ondblclick", function(evt) {
evt = evt || window.event;
evt.returnValue = false; // stop the event
evt.cancelBubble = true; // don't bubble the event
});
}
Also, you should not be using inline HTML event attributes (onmouseover, onmouseout, etc.). Here's why. Instead, you should be doing all your JavaScript work in a dedicated script and use .addEventListener() (or the above attachEvent() method for IE 8 or less).

How to call a function when default browser autocomplete list item selected [duplicate]

I have a pretty simple form. When the user types in an input field, I want to update what they've typed somewhere else on the page. This all works fine. I've bound the update to the keyup, change and click events.
The only problem is if you select an input from the browser's autocomplete box, it does not update. Is there any event that triggers when you select from autocomplete (it's apparently neither change nor click). Note that if you select from the autocomplete box and the blur the input field, the update will be triggered. I would like for it to be triggered as soon as the autocomplete .
See: http://jsfiddle.net/pYKKp/ (hopefully you have filled out a lot of forms in the past with an input named "email").
HTML:
<input name="email" />
<div id="whatever"><whatever></div>
CSS:
div {
float: right;
}
Script:
$("input").on('keyup change click', function () {
var v = $(this).val();
if (v) {
$("#whatever").text(v);
}
else {
$("#whatever").text('<whatever>');
}
});
I recommending using monitorEvents. It's a function provide by the javascript console in both web inspector and firebug that prints out all events that are generated by an element. Here's an example of how you'd use it:
monitorEvents($("input")[0]);
In your case, both Firefox and Opera generate an input event when the user selects an item from the autocomplete drop down. In IE7-8 a change event is produced after the user changes focus. The latest Chrome does generate a similar event.
A detailed browser compatibility chart can be found here:
https://developer.mozilla.org/en-US/docs/Web/Events/input
Here is an awesome solution.
$('html').bind('input', function() {
alert('test');
});
I tested with Chrome and Firefox and it will also work for other browsers.
I have tried a lot of events with many elements but only this is triggered when you select from autocomplete.
Hope it will save some one's time.
Add "blur". works in all browsers!
$("input").on('blur keyup change click', function () {
As Xavi explained, there's no a solution 100% cross-browser for that, so I created a trick on my own for that (5 steps to go on):
1. I need a couple of new arrays:
window.timeouts = new Array();
window.memo_values = new Array();
2. on focus on the input text I want to trigger (in your case "email", in my example "name") I set an Interval, for example using jQuery (not needed thought):
jQuery('#name').focus(function ()
{
var id = jQuery(this).attr('id');
window.timeouts[id] = setInterval('onChangeValue.call(document.getElementById("'+ id +'"), doSomething)', 500);
});
3. on blur I remove the interval: (always using jQuery not needed thought), and I verify if the value changed
jQuery('#name').blur(function ()
{
var id = jQuery(this).attr('id');
onChangeValue.call(document.getElementById(id), doSomething);
clearInterval(window.timeouts[id]);
delete window.timeouts[id];
});
4. Now, the main function which check changes is the following
function onChangeValue(callback)
{
if (window.memo_values[this.id] != this.value)
{
window.memo_values[this.id] = this.value;
if (callback instanceof Function)
{
callback.call(this);
}
else
{
eval( callback );
}
}
}
Important note: you can use "this" inside the above function, referring to your triggered input HTML element. An id must be specified in order to that function to work, and you can pass a function, or a function name or a string of command as a callback.
5. Finally you can do something when the input value is changed, even when a value is selected from a autocomplete dropdown list
function doSomething()
{
alert('got you! '+this.value);
}
Important note: again you use "this" inside the above function referring to the your triggered input HTML element.
WORKING FIDDLE!!!
I know it sounds complicated, but it isn't.
I prepared a working fiddle for you, the input to change is named "name" so if you ever entered your name in an online form you might have an autocomplete dropdown list of your browser to test.
Detecting autocomplete on form input with jQuery OR JAVASCRIPT
Using: Event input. To select (input or textarea) value suggestions
FOR EXAMPLE FOR JQUERY:
$(input).on('input', function() {
alert("Number selected ");
});
FOR EXAMPLE FOR JAVASCRIPT:
<input type="text" onInput="affiche(document.getElementById('something').text)" name="Somthing" />
This start ajax query ...
The only sure way is to use an interval.
Luca's answer is too complicated for me, so I created my own short version which hopefully will help someone (maybe even me from the future):
$input.on( 'focus', function(){
var intervalDuration = 1000, // ms
interval = setInterval( function(){
// do your tests here
// ..................
// when element loses focus, we stop checking:
if( ! $input.is( ':focus' ) ) clearInterval( interval );
}, intervalDuration );
} );
Tested on Chrome, Mozilla and even IE.
I've realised via monitorEvents that at least in Chrome the keyup event is fired before the autocomplete input event. On a normal keyboard input the sequence is keydown input keyup, so after the input.
What i did is then:
let myFun = ()=>{ ..do Something };
input.addEventListener('change', myFun );
//fallback in case change is not fired on autocomplete
let _k = null;
input.addEventListener( 'keydown', (e)=>_k=e.type );
input.addEventListener( 'keyup', (e)=>_k=e.type );
input.addEventListener( 'input', (e)=>{ if(_k === 'keyup') myFun();})
Needs to be checked with other browser, but that might be a way without intervals.
I don't think you need an event for this: this happens only once, and there is no good browser-wide support for this, as shown by #xavi 's answer.
Just add a function after loading the body that checks the fields once for any changes in the default value, or if it's just a matter of copying a certain value to another place, just copy it to make sure it is initialized properly.

Cross-browser: detect blur event on window

I just read, I think all the thread that deals with this subject, and I can't find a real solution to my problem.
I need to detect when the browser window loses its focus, i.e. a blur event.
I've tried all the scripts on stackoverflow, but there doesn't seem to be a proper cross-browser approach.
Firefox is the problematic browser here.
A common approach using jQuery is:
window.onblur = function() {
console.log('blur');
}
//Or the jQuery equivalent:
jQuery(window).blur(function(){
console.log('blur');
});
This works in Chrome, IE and Opera, but Firefox doesn't detect the event.
Is there a proper cross-browser way to detect a window blur event?
Or, asked differently, is there a way to detect a window blur event with the Firefox browser?
Related questions and research:
See Firefox 3 window focus and blur
According to the following github articles, jQuery has discontinued support for Firefox blur testing:
https://github.com/jquery/jquery/pull/1423
http://bugs.jquery.com/ticket/13363
I tried both:
document.addEventListener('blur', function(){console.log('blur')});
and
window.addEventListener('blur', function(){console.log('blur')});
and they both worked in my version of FF (33.1).
Here's the jsfiddle: http://jsfiddle.net/hzdd06eh/
Click inside the "run" window and then click outside it to trigger the effect.
The document.hasFocus (MDN) is an implementation that can resolve the problem with Firefox, but in Opera it isn't supported. So, a combined approach can reach out the problem you are facing.
The function below exemplifies how can you use this method:
function getDocumentFocus() {
return document.hasFocus();
}
Since your question isn't clear enough about the application (timed, pub/sub system, event driven, etc), you can use the function above in several ways.
For example, a timed verification can be like the one implemented on this fiddle (JSFiddle).
It appears that jQuery no longer supports these tests for FireFox:
jQuery bug ticket is here: http://bugs.jquery.com/ticket/13363
jQuery close/deprecation commit is here: https://github.com/jquery/jquery/pull/1423
I am searching for a better way to support Firefox blur eventing, but until I find a better approach, this is a more current status relative to the original accepted answer.
You can use jQuery's blur method on window, like so:
$(document).ready(function() {
$(window).blur(function() {
// Put your blur logic here
alert("blur!");
});
});
This works in Firefox, IE, Chrome and Opera.
I tried using the addEventListener DOM function
window.addEventListener('blur', function(){console.log('blur')});
window.addEventListener('click', function(event){console.log(event.clientX)});
I got it to work after the first blur. but it didnt work when I didnt have the click function attached to it.
There might be some kind of refresh that happens when a click function is interpreted
Here is an alternative solution to your question but it uses the Page Visibility API and Solution is Cross Browser compatible.
(function() {
var hidden = "hidden";
// Standards:
if (hidden in document)
document.addEventListener("visibilitychange", onchange);
else if ((hidden = "mozHidden") in document)
document.addEventListener("mozvisibilitychange", onchange);
else if ((hidden = "webkitHidden") in document)
document.addEventListener("webkitvisibilitychange", onchange);
else if ((hidden = "msHidden") in document)
document.addEventListener("msvisibilitychange", onchange);
// IE 9 and lower:
else if ("onfocusin" in document)
document.onfocusin = document.onfocusout = onchange;
// All others:
else
window.onpageshow = window.onpagehide = window.onfocus = window.onblur = onchange;
function onchange(evt) {
var v = "visible",
h = "hidden",
evtMap = {
focus: v,
focusin: v,
pageshow: v,
blur: h,
focusout: h,
pagehide: h
};
evt = evt || window.event;
if (evt.type in evtMap) {
console.log(evtMap[evt.type]);
} else {
console.log(this[hidden] ? "hidden" : "visible");
}
}
// set the initial state (but only if browser supports the Page Visibility API)
if (document[hidden] !== undefined)
onchange({
type: document[hidden] ? "blur" : "focus"
});
})();

Firefox onchange not calling function

I have a form that contains input:
<input onchange="checkDomain(true); return false;" type="text" id="dsearch" value="" name="domain" maxlength="30"/>
Which works just fine in Opera, Chrome and IE - but Firefox and Safari are having problems with calling the function checkDomain(). I added a line into the function for debugging:
function checkDomain(check)
{
console.log('checkDomain() called!');
// do rest of the stuff...
}
So, Chrome/Opera/IE calls the function with no problem after you enter text and click somewhere else - but Firefox/Safari doesn't. Anyone have a clue?
I cannot remember where I read it, but you should use .keydown()/.keyup()/.keypress() (whatever suits your needs) instead of onchange. At least for input[type=text].
you can use .blur() and .focus for their respective purposes too.
Seeing this in your question: "after you enter text and click somewhere else", makes me conclude you need the .blur() function.
$("input[type=text]").blur(function(){
console.log('checkDomain() called!')
});
maybe onblur is best for this:
<input onblur="checkDomain(true); return false;" type="text" id="dsearch" value="" name="domain" maxlength="30"/>
This problem happens when you change the behavior of your input keypress and key down.
You need to manually call the onchange trigger to fire it.
As an example consider you have a jQuery function for your inputs which do some stuff when user clicks on keyboard.
You need to call input.trigger("onchange"); to make sure the onchange is fired after keypress and keydown
/**
* Keyboard Manager
*/
(function($) {
$.fn.inputManager = function(options) {
};
options = $.extend(defaults, options);
// The key down event only use to manage key board language changes
var keyDown = function(e) {
//Do something
};
var keyPress = function(e) {
//Do something
};
return this.each(function() {
var input = $(this);
//The Firefox dose not trigger the input onchange when you change keypress and key down
//functions. So manually call it!
input.keypress(function(e) {
keyPress(e);
input.trigger("onchange");
});
input.keydown(function(e) {
keyDown(e);
input.trigger("onchange");
});
});
};
})(jQuery);

How can I bind to the change event of a textarea in jQuery?

I want to capture if any changes happened to <textarea>. Like typing any characters (deleting,backspace) or mouse click and paste or cut. Is there a jQuery event that can trigger for all those events?
I tried change event, but it triggers the callback only after tabbing out from the component.
Use: I want to enable a button if a <textarea> contains any text.
Try this actually:
$('#textareaID').bind('input propertychange', function() {
$("#yourBtnID").hide();
if(this.value.length){
$("#yourBtnID").show();
}
});
DEMO
That works for any changes you make, typing, cutting, pasting.
bind is deprecated. Use on:
$("#textarea").on('change keyup paste', function() {
// your code here
});
Note: The code above will fire multiple times, once for each matching trigger-type. To handle that, do something like this:
var oldVal = "";
$("#textarea").on("change keyup paste", function() {
var currentVal = $(this).val();
if(currentVal == oldVal) {
return; //check to prevent multiple simultaneous triggers
}
oldVal = currentVal;
//action to be performed on textarea changed
alert("changed!");
});
jsFiddle Demo
Use an input event.
var button = $("#buttonId");
$("#textareaID").on('input',function(e){
if(e.target.value === ''){
// Textarea has no value
button.hide();
} else {
// Textarea has a value
button.show();
}
});
This question needed a more up-to-date answer, with sources. This is what actually works (though you don't have to take my word for it):
// Storing this jQuery object outside of the event callback
// prevents jQuery from having to search the DOM for it again
// every time an event is fired.
var $myButton = $("#buttonID")
// input :: for all modern browsers [1]
// selectionchange :: for IE9 [2]
// propertychange :: for <IE9 [3]
$('#textareaID').on('input selectionchange propertychange', function() {
// This is the correct way to enable/disabled a button in jQuery [4]
$myButton.prop('disabled', this.value.length === 0)
}
1: https://developer.mozilla.org/en-US/docs/Web/Events/input#Browser_compatibility
2: oninput in IE9 doesn't fire when we hit BACKSPACE / DEL / do CUT
3: https://msdn.microsoft.com/en-us/library/ms536956(v=vs.85).aspx
4: http://api.jquery.com/prop/#prop-propertyName-function
BUT, for a more global solution that you can use throughout your project, I recommend using the textchange jQuery plugin to gain a new, cross-browser compatible textchange event. It was developed by the same person who implemented the equivalent onChange event for Facebook's ReactJS, which they use for nearly their entire website. And I think it's safe to say, if it's a robust enough solution for Facebook, it's probably robust enough for you. :-)
UPDATE: If you happen to need features like drag and drop support in Internet Explorer, you may instead want to check out pandell's more recently updated fork of jquery-splendid-textchange.
2018, without JQUERY
The question is with JQuery, it's just FYI.
JS
let textareaID = document.getElementById('textareaID');
let yourBtnID = document.getElementById('yourBtnID');
textareaID.addEventListener('input', function() {
yourBtnID.style.display = 'none';
if (textareaID.value.length) {
yourBtnID.style.display = 'inline-block';
}
});
HTML
<textarea id="textareaID"></textarea>
<button id="yourBtnID" style="display: none;">click me</div>
Here's another (modern) but slightly different version than the ones mentioned before. Tested with IE9:
$('#textareaID').on('input change keyup', function () {
if (this.value.length) {
// textarea has content
} else {
// textarea is empty
}
});
For outdated browsers you might also add selectionchange and propertychange (as mentioned in other answers). But selectionchange didn't work for me in IE9. That's why I added keyup.
try this ...
$("#txtAreaID").bind("keyup", function(event, ui) {
// Write your code here
});
Try to do it with focusout
$("textarea").focusout(function() {
alert('textarea focusout');
});
.delegate is the only one that is working to me with jQuery JavaScript Library v2.1.1
$(document).delegate('#textareaID','change', function() {
console.log("change!");
});
After some experimentation I came up with this implementation:
$('.detect-change')
.on('change cut paste', function(e) {
console.log("Change detected.");
contentModified = true;
})
.keypress(function(e) {
if (e.which !== 0 && e.altKey == false && e.ctrlKey == false && e.metaKey == false) {
console.log("Change detected.");
contentModified = true;
}
});
Handles changes to any kind of input and select as well as textareas ignoring arrow keys and things like ctrl, cmd, function keys, etc.
Note: I've only tried this in FF since it's for a FF add-on.
Try this
$('textarea').trigger('change');
$("textarea").bind('cut paste', function(e) { });

Categories

Resources