Limit blur event on use type key event
I have a keyup event and a blur event for one object. The enter key works fine. But as soon as focus is lost, unnecessary blur occurs. How can I limit the blur when I use the keyup event.
Actually I need to do the same operation on keyup and blur event. The user will set something either by typing or by simply focusing.
Here's my example.
$('.classname').on({
keyup: function (e) {
if (e.keyCode == 13) {
//Some Code
}
},
blur: function (e) {
//Some code
}
});
+3
source to share
2 answers
var enterKeyPressed = false;
$('.classname').on({
keyup: function(e) {
if (e.keyCode == 13) {
//Some Code
enterKeyPressed = true;
console.log('Enter key');
}
},
blur: function(e) {
if (enterKeyPressed) {
//Some code
enterKeyPressed = false;
}
console.log('Blur');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<input type="text" class="classname" />
0
source to share
You can combine handler functions if they are the same. This can be done as follows. And use event.stopImmediatePropogation () (mentioned by @Gurupasad Rao in his comment) inside this generic function:
$(".classname").bind('blur keyup', function(e){
// Stuff that your function does...
if(enterKeyPressed){
e.stopImmediatePropogation();
}
});
0
source to share