Reputation: 2607
I'm trying to bind two events using jquery. One is keypress and one is left click event. I'm not able to do that. Here is my code
$("#newstaggered-carousel input[name='otherCityInputField']").keypress(function (e) {
Along with that I want to add a left click event. How do I manage that?
Upvotes: 0
Views: 630
Reputation: 1234
There could be multiple ways to achieve this, assuming you need different behaviuors for each event is:
$("#newstaggered-carousel input[name='otherCityInputField']").keypress(function (e) { ... });
$("#newstaggered-carousel input[name='otherCityInputField']").click(function (e) { ... });
Otherwise , you can just do this in order to bind multiple events to the same handler:
$("#newstaggered-carousel input[name='otherCityInputField']").on("click keypress", function(e) { ... }
Upvotes: 0
Reputation: 1014
You can use .on() to bind a function to multiple events:
$('"#newstaggered-carousel input[name='otherCityInputField']"').on('keypress click', function() {
// dosomething
});
Or you can even do like this,
var myFunction = function() {
// dosomething
}
$('#newstaggered-carousel input[name='otherCityInputField']')
.keypress(myFunction)
.click(myFunction)
or do like this,
$('#newstaggered-carousel input[name='otherCityInputField']').bind('keypress click', function(){
//do something
});
Upvotes: 0
Reputation: 115222
You can use on()
to bind multiple events by space separated. For getting fired event type you can use event.type
$("#newstaggered-carousel input[name='otherCityInputField']").on('keypress click',function (e) {
if(e.type=='click'){
//handle click event
}
});
In case you need seperate handlers for them then you can use
$("#newstaggered-carousel input[name='otherCityInputField']").on({
'keypress': function (e) {
//kepress event handler
},'click':function (e) {
//click event handler
}
});
Upvotes: 1
Reputation: 15393
Use .on()
method to bind multiple events together
$("#newstaggered-carousel input[name='otherCityInputField']").on('keypress click', function (event) {
alert(event.type);
});
Upvotes: 0
Reputation: 9508
Answer more specific to detect click and keypress too.
$("#newstaggered-carousel input[name='otherCityInputField']")
.on("keypress click", function (e) {
if (e.type == "click") {
alert("clicked");
}
else{
alert("Key pressed");
}
});
Upvotes: 0
Reputation: 30557
Use on() with a space separating the events
$("#newstaggered-carousel input[name='otherCityInputField']")
.on("keypress click", function (e) {
// Common Event Handler for both the elements
});
If you want to handle both events separately on same element
$("#newstaggered-carousel input[name='otherCityInputField']")
.on('Keypress', function (e) {
// Keypress Handler
}).on('click', function (e) {
// Click Handler
});
Upvotes: 3