onkeypress + onblur in Javascript - javascript

The onblur event in Javascript is triggered when the element loses focus.
The onkeydown occurs on an element that has the focus when a key is pressed down and occurs periodically until the key is released.
If I want to validate a date field, the onkeydown event concerns 9 and 13 (enter and tab key).
But when I press the enter key, then I receive duplicate alert message.
Of course in this case we have two tests, onblur and onkeydown event.
this is the html code :
<html:text onblur="return onDateChange(this);"
onkeydown="return onDateKeyPress(this);"/>
the onDateChange() method is :
function onDateChange(obj){
//validateField is an externatl javascript method which trigger an alert message if we have errors in date
if(validateField(obj,'date',dateFormat)){
//do instructions
}
}
and finally the onDateKeyPress() method is :
function onDateKeyPress(obj){
if(window.event.keyCode == 9)
{
if(validateField(obj,'date',dateFormat))
{
//do instructions
}
}
if(window.event.keyCode == 13)
{
if(validateField(obj,'date',dateFormat))
{
//do instructions
}
}
}
So, the problem is to have one display alert message.
Any suggestions?

you can do it easily with jquery
$('#text_field_id').bind({
blur: function(event) {
if(validateField(this,'date',dateFormat)){
//do instructions
}
},
keydown: function(event) {
if(event.keyCode == 9)
{
if(validateField(this,'date',dateFormat))
{
//do instructions
}
}
if(event.keyCode == 13)
{
if(validateField(this,'date',dateFormat))
{
//do instructions
}
}
}
});
you dont need to include onclick or onkeydown in your text element. One small question you want to execute same instructions in all cases or different instructions???? if you want to execute same instructions, lot of codes can be removed.

In the solution above; keydownFired is true when blur is fired and the if branch of the code does nothing. so nothing happens.
If the blur has something to do other than showing alert; then the follwoing should work.
input.addEventListener('blur', function (e) {
doSomethingThatshldHappenAlwaysOnBLur();
if (keydownFired) {
keydownFired = false
} else {
showAlert();
}
})

Recently I had a problem with having onkeypress and onblur attached to one element. One of the major problems with onkeypress and onkeyblur is that they by nature will trigger each other :) (Triggered? Get it? That's a joke btw. I am bad at jokes, sorry!)
The solution is simple and stupid. Instead of having an alert when onkeypress happens AND when onblur happens you trigger only onblur. How?
//I gave this thing and id. You should always give your things and id. Ids are cool and I love them.
<html:text id="thisIsMyId"
onblur="return onDateChange(this);"
onkeydown="return onDateKeyPress(this)";
/>
the onDateChange() method will stay pretty much the same:
//This will stay the same, you will see why, soon
function onDateChange(obj){
//ValidateField is an externatl javascript method which trigger an alert message if we have errors in date
//If you might have noticed tha **this validate** function is used 3 times, why?
if(validateField(obj,'date',dateFormat)){
//do instructions and **I assume the alert?**
}
}
Now, we will make onDateKeyPress() a little bit blurry :)
//Here is where we strike
function onDateKeyPress(obj){
//This looks weird but it checks if the keycode actually works in the browswer
var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
//Instead of having 2 ifs just make one if with and the logical operator "or" :)
if(keycode == 13 || keycode == 9){
//I am not sure if oyu need to use this but in the example I had, I had to use
//my validation-function otherwise it would just submit
if(validateField(this,'date',dateFormat)){
//If you have a submit form or something this can help
event.stopPropagation();
//we just trigged the onBlur Handler by "blurring" this thing :)
document.getElementById('thisIsMyId').blur();
}
}
With this we did cut one validation and have to write the logic only once. Only in the onDateChange() function.
If someone can make it even better please comment below. I would like to make the code even shorter.
At the end of the day it still depends on the specific situation. It worked for me but this is not a "fits-all-solution".

Related

jquery - add an event handler to an object population

im sorry but I don't know how to call this code. Hence, the title.
$("#e12").select2({
width: "resolve",
tags: ["Cardiologist", "Anesthesiologist", "Neurologist", "Gynecologist", "Andrologist"]
});
That is the code that is populating my input element. However, I want to add an event handler for that. How can I add this?
$('#e12').keypress(function(event) {
if (event.keyCode == 13) {
event.preventDefault();
}
});
P.S. Please tell me what my first code is called.
Your first code is using select2 plugin and is initializing your input with data, which will be used by that input after on.
And use keydown
$('#e12').on("keydown",function(event) {
if (event.keyCode == 13) {
event.preventDefault();
}
});
They're a little different. In this case, keypress isn't inserting anything into your field.

jQuery - detect change event triggered programmatically

I have a jQuery change event for when a user changes a given SELECT element. However the event may also be triggered by a third party script. What I want to do is detect whether the event was triggered programmatically or by the user.
I have tried the accepted solution in this question Check if event is triggered by a human
But note the JSFiddle in this answer is for a click event rather than a change event.
To demonstrate I amended the fiddle and created this one: http://jsfiddle.net/Uf8Wv/231/
If you try this in latest Firefox or Chrome, you will see that the alert human is being shown even when the event was triggered programmatically.
I have tried event.originalEvent.isTrusted but that doesn't work in all browsers. Can anyone help?
I have added mouseenter and mouseleave events. The idea is that it's a human if the click coincided with a mousepointer being over the element. See:
http://jsfiddle.net/Uf8Wv/232/
$("#try").mouseenter(function(event) {
mouseover = true;
});
// ... etc.
I can't think of any other way.
You can find some vague difference between click and emulated click using this code:
$(document).on('change', "#try", function (event) {
//some difference appear in the next line
console.log(event.delegateTarget.activeElement);
//no difference
if (event.originalEvent === undefined) {
alert('not human')
} else {
alert(' human');
}
event.delegateTarget = null;//doesn't help
});
$('#click').click(function (event) {
$("#try").click();
});
Click on the checkbox logs <input id="try" type="checkbox">.
Click on the button logs <button id="click">.
But...
Run $("#try").click(); from console before any clicks logs <body> and after the click result of the last click.
Generally JS can always fake any client event. So isTrusted is never trusted.
You can listen to the click event as well, and modify a variable. The change event seems indeed to be quite similar wheter it's a real click or a script triggered click, but the click on #try event won't be the same. And since click is triggered before change, you have time to set a switch.
Like this for example:
var realClick;
$("#try").change(function(event) {
console.log('change')
if (!realClick) {
alert('not human')
} else {
alert(' human');
}
});
$("#try").click(function(event) {
console.log('click')
// originalEvent is one way, but there will be many differences
if (event.originalEvent) {
realClick = true;
} else {
realClick = false;
}
});
// Since this is called from outside, better not put
// any controls here.
$('#click').click(function(event) {
$("#try").click();
});
http://jsfiddle.net/2xjjmo09/3/
What really worked for me is:
if ((event.originalEvent.isTrusted === true && event.originalEvent.isPrimary === undefined) || event.originalEvent.isPrimary === true) {
//Hey hooman it is you
//Real CLick
}
Tested with jQuery version 3.5
You can easily detect whether the click event on the button is actually triggered by mouse click or not. By doing,
$('#click').click(function(ev) {
if (ev.which !== undefined && ev.button !== undefined) {
$("#try").click();
}
});
Here's the Fiddle
Note: Beware of either ev.which or ev.button could result in 0 on some browser for left-click.
You can check for if event.srcElement (which is source element on which event is triggered) is equal to event.currentTarget something like:
$("#try").change(function(event) {console.log(event,event.target,event.currentTarget,event.srcElement)
if (event.currentTarget=== event.srcElement) {
alert(' human')
} else {
alert(' not human');
}
});
Fiddle: http://jsfiddle.net/Uf8Wv/234/

Handling events for mouse click and keydown or keypress (for non-modifier keys)

I am new to JS and trying to learn on my own - thanks for any help!
I am trying to have a simple program respond to a click differently depending on what other key is pressed at the time of the mouse click.
I have searched far and wide and have not been able to find an answer that works for non-modifier keys alt and shift (which I have had no trouble implementing). However, I can't for the life of me figure out how to achieve the same result with a regular character key.
The example below (which I found in other comments on this site) works if the alt key is employed.
<div id="targetDiv">I want to put a ding in the universe.</div>
$(function() {
$("#targetDiv").click(function(event) {
if (event.altKey) {
//do something, alt was down when clicked
}
});
});
However, the intuitive modification does not work.
For example, the otherwise identical code (now using event.keyCode===114) does not work (?!) when the 'r' key is pressed (nor does event.charCode===114 do the trick):
<div id="targetDiv">I want to put a ding in the universe.</div>
$(function() {
$("#targetDiv").click(function(event) {
if (event.keyCode===114) {
//do something, alt was down when clicked
}
});
});
What went wrong?
I am able to get functionality out of a keyPress if I listen to it alone:
addEventListener("keypress", rIsPressed, false);
function rIsPressed(event){
if(event.keyCode===114){
console.log("the 'r' key is pressed");
}
}
however nothing seems to work when I try to pair a character keypress with a mouse click or even a character keypress with a modifier keypress:
addEventListener("keypress", rIsPressed, false);
function rIsPressed(event){
if((event.keyCode===114) && (event.altKey)){
console.log("the 'alt' and 'r' keys are pressed");
}
}
Note: I have tried keydown instead of keypress in all of these examples with no success.
Suggestions please on what I am missing or overlooking - what is problematic about pairing a character key down/press with a modifier key or a mouse click !?
Thank you!!
As I commented above, the click event does not have a property called keyCode so doing event.keyCode will not work. The only reason that control and alt work is because they are properties of the click event, event.ctrlKey and event.altKey. You can be a little more creative and use something like this maybe though I don't really know what you need:
var currKey = null;
$("#targetDiv").click(function (event) {
if (currKey != null) {
$("#targetDiv").text(currKey);
}
});
$(window).keydown(function (event) {
currKey = event.which;
});
$(window).keyup(function (event) {
currKey = null;
});
This stores the key code when keydown is fired, when keyup is fired it clears the var. The stuff in the click event is only allowed to run if the var shows something other than null.

jQuery plugin not firing correction keydown or idle events

I am programming a jQuery plugin which tracks specific events. I have provided 2 JSFiddle examples for the sanitised code to assist at the end of the question.
I am struggling to fathom why 2 particular events are not firing. The first function tracks when the user triggers the backspace or delete keys within an input or textarea field. The code for this:
// Keydown events
$this.keydown(function (e) {
var keyCode = e.keyCode || e.which;
// Tab key
if (e.keyCode === 9) {
alert('tab key');
} else if (e.keyCode === 8 || e.keyCode === 46) { // Backspace and Delete keys
if ($this.val() !== '') {
alert('Backspace or delete key');
}
}
});
I only wish to track the error-correction keys when a field is not empty. The tab key in the above example works as expected within the conditional statement. The backspace and delete keys do not work when inside the plugin and targeting the element in focus.
The second event not firing is tracking whether a user becomes idle. It is making use of jQuery idle timer plugin to manipulate the element in focus.
// Idle event
$this.focus(function() {
$this.idleTimer(3000).bind('idle.idleTimer', function() {
alert('Gone idle');
});
}).focusout(function() {
$this.idleTimer('destroy');
});
With both of these events I have refactored the code. They were outside of the plugin and targeted $('input, select, textarea') and worked as expected. I have brought them inside the plugin, and set them to $(this) to manipulate elements currently in focus. For most of the functions, this has worked without fault, but these 2 are proving problematic.
The first JSFiddle is with the 2 functions inside the plugin. tab works, whereas the correction keys do not. Strangely, in this example the idle function is firing (it does not in my dev environment). As this is working in the JSFiddle, I accept this may be difficult to resolve. Perhaps suggestions on handling an external plugin within my own to remedy this?
Fiddle 1
The second JSFiddle has taken the backspace and delete key functionality outside of the plugin and targets $('input, select, textarea') and now works.
Fiddle 2
For Fiddle1:
if ($this.val() !== '') {
alert('Backspace or delete key');
}
Look at what $this actually is.

Prevent Enter key works as mouse click

I noticed that if you focus on an element that mouse clic can be triggered, the Enter keys acts like as you left click the mouse. I want to avoid this running since it comes into conflict in other pieces of my code.
In the following example if I focus on this imageButton and I clic once, the next clicks can be "done" with the Enter key, so I don't want this because this button fires a slideToggle() and shows a hidden div, so IMO it's pointless toggle this div with the keyboard.
Is there any way to make it global way?
Thank you.
Try this:
$(".myElements").keypress(function(e) {
if (e.which == 13) {
e.preventDefault();
}
});
It will stop the enter key behaviour only, allowing the other key functions to work as usual.
Listen for "keypress" and .preventDefault()
ex. with <myelm class="nokey"/>
function noKeyPressing(){
var elms = document.getElementsByClassName('nokey'),
stop = function stop(e){ return e.preventDefault(), false; },
i = elms.length;
while(--i >= 0){
elms[i].addEventListener('keypress', stop, true);
}
}
noKeyPressing()
If you just want to prevent Enter then the keyCode to look for is 13.
try
.unbind('keydown');
to disable all key events on your element
You can return false to prevent the default action.
<input type="submit" onkeypress="return false;" value="Submit" />
An other possible way i think:
$('.elems').on('click',function(){$(this).blur()});
try this code
$('body *').keypress(function (e) {
if (e.which == 13) {
e.preventDefault();
}
});
the above code will prevent pressing enter for every element in page
,You can change the selector $('body *') to something else depending to your case

Categories