How do I create a custom onEnter event in jQuery? - javascript

I would like to create a custom event in jQuery that captures ENTER onkeypress events, so that I would not have to code this way every time:
if(e.keyCode == 13) {
// event code here
}
In other words, I would like to be able to code like this:
$("selector").bind("enter", function(){
// event code here
});

Modern jQuery (1.7 and up) uses .on() to bind event handlers:
// delegate binding - replaces .live() and .delegate()
$(document.body).on("keyup", ":input", function(e) {
if(e.which == 13)
$(this).trigger("enter");
});
// direct binding - analogous to .keyup()
$(":input").on("keyup", function(e) {
if(e.which == 13)
$(this).trigger("enter");
});
Older versions of jQuery use one of the following methods. You could have a single .live() or .delegate() event handler for all elements. Then use that to trigger your custom event, like this:
$(document.body).delegate(":input", "keyup", function(e) {
if(e.which == 13)
$(this).trigger("enter");
});
Not for any :input element you could do exactly what you have:
$("selector").bind("enter", function(){
//enter was pressed!
});
You can test it out here.

$("selector").keyup(function (e) {
if (e.keyCode == 13) {
$(this).trigger("enter");
}
}).bind("enter", function () {
// event code here
});
It is a good idea to use namespaced event names, to reduce the chance of accidentally clashing with other jQuery code that uses custom events. So instead of "enter" you could use "enter.mywebapp" or something similar. The makes the more sense the more custom events you use.

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.

Track first keypress event

For reasons I have to rely on keypress instead of keydown/keyup. keypress repeatedly fires events if the key is pressed. How to track only the first press on a key?
For keydown/keyup this would not be a problem, since there is a dedicated keyup event. But this is not the case for keypress.
Check the 'repeat' property of the event (https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent)
If it's false then it's the first event, true otherwise.
Example using jquery:
$("#someid").on("keypress", function(e){
if(!e.originalEvent.repeat){console.log("first keypress")};
})
It's true that the "repeat" attribute doesn't work in Safari. It's only available in Gecko-based browsers. In lieu of that, try this (if you absolutely MUST use "keypress" instead of the alternatives):
var lastCode = -1;
$("#someid").on("keypress", function(e) {
var code = e.keyCode || e.which;
if (lastCode !== code) {
// do something
}
lastCode = code;
});

How to stop an event if not triggered directly?

Lets say there is a textbox and a button. On the click of button a function is executed, and on the focusout of textbox, the button is clicked. What I wanna know is, is there a way, I can determine that weather the user clicked the button, or it was triggered by focusout event of textbox, so that I may do some custom work in the click event, if it was triggered by focusout of textbox?
I could write some code, but I don't even have any idea where to begin with, I know the jQuery event and event.which property, but I wonder if it/they could be useful in this situation?
you can use event.target to determine which DOM element has initiated the event, then you can check if this is the button or the textbox.
check this out for more information: http://api.jquery.com/event.target/
from the documetation:
event.target
The target property can be the element that registered for the event
or a descendant of it. It is often useful to compare event.target to
this in order to determine if the event is being handled due to event
bubbling. This property is very useful in event delegation, when
events bubble.
This depends on how you're triggering the function from the textarea blur event, if you're simply triggering the click event using the following approach:
$('#btn').click(
function(e){
buttonActivation(e);
});
$('#txt').blur(
function(e){
$('#btn').click();
});
Then I'd suggest evaluating the originalEvent object to see what the original event was (if there was no originalEvent then the function was called by a programmatic click event, with jQuery; whereas if the originalEvent.type evaluates to click then the button must have been clicked.
function buttonActivation(e) {
if (!e) {
return false;
}
else {
var oEvent = e.originalEvent;
if (oEvent === undefined) {
console.log('Programmatic event');
}
else if (oEvent.type == 'click') {
console.log('User-initiated event');
}
}
}
JS Fiddle demo.
If, however, you're using something like the following (simply calling the same function from a different place):
$('#btn').click(
function(e){
buttonActivation(e);
});
$('#txt').blur(
function(e){
buttonActivation(e);
});
Then I'd recommend either directly assessing e.target or e.type:
function buttonActivation(e) {
if (!e) {
return false;
}
else {
var oEvent = e.type;
if (oEvent === 'blur') {
console.log('Programmatically-triggered event, on ' + oEvent);
}
else if (oEvent == 'click') {
console.log('User-initiated ' + oEvent + ' event');
}
}
}
JS Fiddle demo.
You can use the event.target. By default, jquery provides the event to the handler function.
Here's an example : jsfiddle
You can pass an additional parameters when triggering the event and check them in event handler.
So if you wrote
button$.trigger('click', 'hello');
then you can write the handler like
button$.on('click', function(e, someStr) {
console.log(someStr || 'Nothing passed');
// Obviously if someStr is undefined, the user clicked the button,
// otherwise the $.trigger() method has been called.
});

Catch javascript event on fields created dynamically

I have an input field with class named "form_inputext1".
I am doing some action when pressing ENTER, using this code:
jQuery(".form_inputext1").keypress(function(event) {
console.log(event.keyCode);
if (event.keyCode == '13' || event.which == '13') {
event.preventDefault();
jQuery("#addMoreOptions").click();
return false;
}
});
This part works fine. One of the things it does is it adds one more input field of class "form_inputext1" as a result of an ajax call.
The problem is this newly added field is not associated with the keypress event I wrote. I assume that's because the jQuery code only attach the event to the existing fields, not to the fields added in the future.
How can I work around this? I want this function to apply to onkeypress even for inputs that are not in the DOM yet.
YOu can use Jquery's live:
jQuery(".form_inputext1").live('keypress', function(event) {
console.log(event.keyCode);
if (event.keyCode == '13' || event.which == '13') {
event.preventDefault();
jQuery("#addMoreOptions").click();
return false;
}
});
Or you can add the keypress event when you create the element, which will give you much better performance:
$('.clicker').click(function() {
$('<div class="clicker" />').text('new').appendTo($(this)).keypress(function(event) {
alert(event.which);
})
})
Example of that
Use .live() or .delegate() instead.
http://api.jquery.com/live/
http://api.jquery.com/delegate/
If you use the jQuery live method to bind an event to a class, it will apply even to elements that are added to the DOM after you call the live method.
Documentation: http://api.jquery.com/live/
From the documentation:
To bind a click handler to the target element using this method:
$('.clickme').live('click', function() {
// Live handler called.
});
And then later add a new element:
$('body').append('Another target');
Then clicks on the new element will also trigger the handler.
Use .live():
$('.form_inputext1').live('keypress', function ( event ) {
});

document.onkeyup ported to jQuery

I'm porting some old Javascript to jQuery:
document.onkeyup = function (event) {
if (!event) window.event;
...
}
this code works on all major browsers. My jQuery code looks like:
$(document).keyup = function (event) {
...
}
however this code is not working (the function is never triggered at least in IE7/8). Why? How to fix?
The jQuery API is different:
$(document).keyup(function (event) {
...
});
jQuery.keyup is a function which takes as an argument the callback. The reason behind it is to let us assign multiple keyup (or whatever) events.
$(document).keyup(function (event) {
alert('foo');
});
$(document).keyup(function (event) {
alert('bar');
});
There's also keyup() without an argument, which will trigger the keyup event associated with the respective element.

Categories