I want to know if the focus event is triggered programtically or by human ?
I am writing the part of the script
jQuery( document ).on( 'focus', '#song_artist_focus', function(event) {
if(event.originalEvent === undefined ){
alert('I am not human');
return;}
alert('I am human') ;
});
And when i call this script programtically like this
jQuery('#song_artist_focus').focus();
It still shows that event is triggred by human. Please help ?
UPDATE
I checked this solution Check if event is triggered by a human. But doesn't work on focus events.
Your problem is that the focus event doesn't bubble.
jQuery fixes that with a little magic to make it more like the other events, but it still doesn't quite work like an event that naturally bubbles.
To fix the problem, use the focusin event instead, as it bubbles, and do .trigger('focusin')
jQuery(document).on('focusin', '#song_artist_focus', function(event) {
if (event.originalEvent === undefined) {
console.log('I am not human');
} else {
console.log('I am human');
}
});
jQuery('#song_artist_focus').trigger('focusin');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="song_artist_focus">
Html :
<input type='text' id='try' >try
<button id='click'>Click</button>
jQuery :
$("#try").focus(function(event) {
if (event.originalEvent === undefined) {
console.log('not human')
} else {
console.log(' human');
}
});
$('#click').click(function(event) {
jQuery('#try').focus();
});
Try it , you will get expected result.
Related
I use the native HTML date pickers. I want to achieve that the parent form is submitted when a date is selected by the datepickers browsers provide.
If the date is input by keyboard, I only want to submit if the enter key is pressed or on focusout.
Now my problem is that I cannot distinguish between date picker input and keyboard input, at least in Firefox. Some examples:
$(this).on('input', function(event) {
console.log(event.type);
}
This always logs 'input', no matter what I do - I would have expected that to be either "click" or "keydown" or something alike.
The on('click') handler only fires when I click on the input field, not when I click something in the date picker...
Can someone push me in the right direction?
Thanks alot
Philipp
I did a workaround which is close to what I want:
$('#eooMainForm input[type="date"]')
.each(function() {
$(this).data('serialized', $(this).serialize());
$(this).on('focusout', function() {
if($(this).serialize() != $(this).data('serialized')) {
$("#eooMainForm").form('submit');
}
});
$(this).on('keypress', function(event) {
$(this).data('byKeyPress', 1);
});
$(this).on('click', function(event) {
$(this).data('byKeyPress', 0);
});
$(this).on('change', function(event) {
//if change was done by date picker click
if($(this).data('byKeyPress') != 1 && $(this).serialize() != $(this).data('serialized')) {
$("#eooMainForm").form('submit');
}
});
});
So a keypress event listener sets the "flag" "byKeyPress" to 1, while a click events listener sets it to zero. This way, I can determine in the change event listener what caused the change.
The only situation where this does not work is when a user starts typing the date but then selects it by clicking the datepicker. I can live with that.
You'll need to attach an event which supports both event types. Using JQuery: $('a.save').bind('mousedown keypress', submitData(event, this));
Then create a JS condition:
function submitData(event, id)
{
if(event.type == 'mousedown')
{
// do something
return;
}
if(event.type == 'keypress')
{
// do something else
return;
}
}
You can find all the list of event in this image.
$('input').on('blur', function(event) {
alert(event.type);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
You can apply all event like the above example. Above example applied blur event on input.
I need to catch when the PageUp/PageDown keys are pressed and an element is scrolled, but I've so far been unable to do so. I've tried
Listening for 'keydown' event**: an event triggers when a non-scrolling element is in focus, but when a scrolling element is in focus, no event fires
$(window).on('keydown', function(e)
{
console.log(e.keyCode === 34);
});
Listening for 'keypress' event**: no event triggers in any context
$(window).on('keypress', function(e)
{
console.log("keypress"); //does nothing
});
Listening for 'scroll' event**: no event triggers in any context
$(window).scroll(function()
{
console.log("scrolling"); //does nothing
});
I'm at a loss and I haven't been able to find any clues.
I've tried my current code in a jsFiddle, and it works fine, so it must be something more specific.
instead of window try to use document so it will consider current document on web page.
in your code there is bracket miss match.
$(document).ready(function(){
$(document).keypress(function(e){
if(e.keyCode === 34){
console.log('page down')
}
});
$(document).keypress(function(e){
console.log("keypress"); //console will print
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
hope this will work for you.
Can you try also ?
$(window).bind('keydown', function(event) {
console.log(event.which === 33) });
The event.which property returns which keyboard key or mouse button was pressed for the event
Actually your syntax is incorrect you are missing a closing ) at the end of your function, you should write:
$(window).on('keydown', function(e) {
console.log(e.keyCode === 34);
});
$(window).on('keypress', function(e) {
console.log("keypress"); //does nothing
});
$(window).scroll(function() {
console.log("scrolling"); //does nothing
});
#scroll {
max-height: 100px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="scroll">
<br>fghfjkjgfj
<br/>dfdfdfdf
<br/>dfdsf
<br/>
<br/>
<br/>dfdfdf
<br/>
<br/>
<br/>ssdsds
<br/>fdf
<br/>
<br/>
<br/>
<br/>fgfgfg
<br/>End
</div>
And everything, will work as expected.
So the element I'm trying to scroll on is a SlickGrid table, and it has its own scrolling event.
So I wrote, based on their docs:
this.grid.onScroll.subscribe(function(e, args)
{
console.log(e);
}
Now it is triggering on Page Down / Page Up key-presses.
focusout on input field will trigger every time the specific input looses its focus.
But, I want to exclude some specific a tag from triggering that focusout function
Example:
<input type="text" id="name_input">
<a id="apply_name">SAVE</a>
Then the focusout function:
$("#name_input").focusout(function(e) {
//do something here
});
Clicking on "#apply_name" also triggers focusout function of an input. How can I exclude that specific element ID from triggering it.
Note: I tried some tricks already posted on StackOverflow and none of them seams to work...
Another way of doing this is checking what your target id is
var evt;
document.onmousemove = function (e) {
e = e || window.event;
evt = e;
}
$("#name_input").focusout(function (e) {
if (evt.target.id == "apply_name") {
//apply_name clicked
} else {
//focus out and applyname not clicked
}
});
DEMO
You can use "blur" - event.
$("#name_input").on("blur", function(e) {
//your code
});
Solution from How to exclude Id from focusout
Added .hasClass which I also needed:
$('#id').focusout (function (e) {
if (e.relatedTarget && $(e.relatedTarget).hasClass('dontFocusOut')) {
return;
}
//do your thing
});
How can I tell if a function being called originated from a click event?
For instance, an anchor or button is clicked and the event is captured and a function is called.
Inside of this function in firebug's stack trace I can see an Object like this
Object { originalEvent=Event click, type="click", timeStamp=97128874, more...}
It says the originalEvent came from a click.
Depending on whether it came from or click or not, processing occurs differently.
Is there a way to tell if the function being called originated from a click event?
Any function that is triggered with an event is sent an event object. Call .type on this object and it will return which event it is. Here is a simple example from the jQuery docs:
$( "a" ).click(function( event ) {
alert( event.type ); // "click"
});
So lets say you want to listen for both clicks and typing in a text input:
$( "input" ).on("click keyup", eventHandler);
But you want to do something special on a click:
eventHandler = function(event){
if (event.type === 'click'){
// code to execute if there is a click
} else {
// code to execute if there is a non-click event
}
// code to execute for both click and non-click events
};
That would be the event.type
var elem = document.getElementById('test');
elem.addEventListener('click', function(event) {
console.log(event.type)
}, false);
FIDDLE
or in jQuery
$('#test').on('click paste mouseenter', function(event) {
console.log(event.type)
});
FIDDLE
See it:
DEMO
$('div').click(test);
function test(e){
if(e && e.type === 'click')
alert('called from click!');
else alert('NOT called from click!');
}
test();
demo
function myFn( evt ){
console.log( evt.type );
}
$('div').on('click mouseenter mouseleave', myFn);
Is there any event in Jquery that's triggered only if the user hits the enter button in a textbox? Or any plugin that can be added to include this? If not, how would I write a quick plugin that would do this?
You can wire up your own custom event
$('textarea').bind("enterKey",function(e){
//do stuff here
});
$('textarea').keyup(function(e){
if(e.keyCode == 13)
{
$(this).trigger("enterKey");
}
});
http://jsfiddle.net/x7HVQ/
$('#textbox').on('keypress', function (e) {
if(e.which === 13){
//Disable textbox to prevent multiple submit
$(this).attr("disabled", "disabled");
//Do Stuff, submit, etc..
//Enable the textbox again if needed.
$(this).removeAttr("disabled");
}
});
Here is a plugin for you: (Fiddle: http://jsfiddle.net/maniator/CjrJ7/)
$.fn.pressEnter = function(fn) {
return this.each(function() {
$(this).bind('enterPress', fn);
$(this).keyup(function(e){
if(e.keyCode == 13)
{
$(this).trigger("enterPress");
}
})
});
};
//use it:
$('textarea').pressEnter(function(){alert('here')})
heres a jquery plugin to do that
(function($) {
$.fn.onEnter = function(func) {
this.bind('keypress', function(e) {
if (e.keyCode == 13) func.apply(this, [e]);
});
return this;
};
})(jQuery);
to use it, include the code and set it up like this:
$( function () {
console.log($("input"));
$("input").onEnter( function() {
$(this).val("Enter key pressed");
});
});
jsfiddle of it here http://jsfiddle.net/VrwgP/30/
It should be well noted that the use of live() in jQuery has been deprecated since version 1.7 and has been removed in jQuery 1.9. Instead, the use of on() is recommended.
I would highly suggest the following methodology for binding, as it solves the following potential challenges:
By binding the event onto document.body and passing $selector as the second argument to on(), elements can be attached, detached, added or removed from the DOM without needing to deal with re-binding or double-binding events. This is because the event is attached to document.body rather than $selector directly, which means $selector can be added, removed and added again and will never load the event bound to it.
By calling off() before on(), this script can live either within within the main body of the page, or within the body of an AJAX call, without having to worry about accidentally double-binding events.
By wrapping the script within $(function() {...}), this script can again be loaded by either the main body of the page, or within the body of an AJAX call. $(document).ready() does not get fired for AJAX requests, while $(function() {...}) does.
Here is an example:
<!DOCTYPE html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var $selector = $('textarea');
// Prevent double-binding
// (only a potential issue if script is loaded through AJAX)
$(document.body).off('keyup', $selector);
// Bind to keyup events on the $selector.
$(document.body).on('keyup', $selector, function(event) {
if(event.keyCode == 13) { // 13 = Enter Key
alert('enter key pressed.');
}
});
});
</script>
</head>
<body>
</body>
</html>
If your input is search, you also can use on 'search' event. Example
<input type="search" placeholder="Search" id="searchTextBox">
.
$("#searchPostTextBox").on('search', function () {
alert("search value: "+$(this).val());
});
//Short and simple solution
$(document).ready(function(){
$('#TextboxId').keydown(function(event){
if (event.which == 13){
//body or action to be performed
}
});
});
HTML Code:-
<input type="text" name="txt1" id="txt1" onkeypress="return AddKeyPress(event);" />
<input type="button" id="btnclick">
Java Script Code
function AddKeyPress(e) {
// look for window.event in case event isn't passed in
e = e || window.event;
if (e.keyCode == 13) {
document.getElementById('btnEmail').click();
return false;
}
return true;
}
Your Form do not have Default Submit Button
Another subtle variation.
I went for a slight separation of powers, so I have a plugin to enable catching the enter key, then I just bind to events normally:
(function($) { $.fn.catchEnter = function(sel) {
return this.each(function() {
$(this).on('keyup',sel,function(e){
if(e.keyCode == 13)
$(this).trigger("enterkey");
})
});
};
})(jQuery);
And then in use:
$('.input[type="text"]').catchEnter().on('enterkey',function(ev) { });
This variation allows you to use event delegation (to bind to elements you haven't created yet).
$('body').catchEnter('.onelineInput').on('enterkey',function(ev) { /*process input */ });
I could not get the keypress event to fire for the enter button, and scratched my head for some time, until I read the jQuery docs:
"The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events." (https://api.jquery.com/keypress/)
I had to use the keyup or keydown event to catch a press of the enter button.
<form name="searchForm" id="searchForm" onsubmit="doSomething(event)">
<input type="text" name="search" id="search">
</form>
<script>
function doSomething(event){
let $val = $('form#searchForm input[name="search"]').val();
console.log($val);
event.preventDefault();
}
</script>
One simple way it can be done in this way. Enter text or number, hit enter key and get the entered input value.