How to combine keypress & on click function in JavaScript? - javascript

I have the following two functions:
$("input").keypress(function(event) {
if (event.which == 13) {
//code
}
});
$('#login_submit').click(function () {
//code
});
The code which is being used in the functions are EXACTLY the same code, basically code dublication. So i was wondering if there is a way to combine these functions with an OR statement??

Create your own callback and pass that to the event handlers.
var callback = function() {...};
$("input").keypress(function() {
if (event.which == 13) callback();
});
$('#login_submit').click(callback);

Add a class to your HTML
<input class="myClass">
<div id="login_submit" class="myClass" ></div>
Now you can write:
$(".myClass").bind("keypress click", function(){});
Or do this:
$("input").add("#login_submit").bind("keypress click", function(){});
Be aware that clicking on the input will also trigger this.

Why don't you do it like this?
$("input").keypress(function(event) {
if (event.which == 13) {
foospace.yourfunction();
}
});
$('#login_submit').click(function () {
foospace.yourfunction();
});
var foospace={};
foospace.yourfunction=function() {
alert("your code goes here!");
}
Edit:
The callback solution by #David is slightly more elegant.

I would chain the events like:
var watchCurrentCursorPosition = function (){
console.log("foo");
}
$("input").keypress(
watchCurrentCursorPosition
).click(
watchCurrentCursorPosition
);

For those who still are looking for an answer to the #Sino's question.
The code which is being used in the functions are EXACTLY the same code, basically code dublication. So i was wondering if there is a way to combine these functions with an OR statement??
JQuery .on() method is the way to go.
Description: Attach an event handler function for one or more events to the selected elements.
So your code could go like this:
$("input").on("click keypress", function(event) {
if (event.which === 13) {
event.preventDefault();
//code
}
});

Related

Using jquery .on when running a function

I have the following line of jquery which reacts to any key up event in any text input on a form. It then runs a function called processPrimarySearch:
$('#primarySearch input[type="text"]').on('keyup', this, processPrimarySearch);
This works, but I want to adapt it so keyup ignores a tab key press as described here: Keyup event behavior on tab
I can't work out how to re-write this as I don't understand how to pass this before calling processPrimarySearch. For example I have the following but it doesn't work and I don't understand what I'm supposed to write to make it work:
$('#primarySearch input[type="text"]').on({
"keyup": function(e) {
if (e.which != 9) {
// No reference to 'this'!
processPrimarySearch();
}
}
});
function processPrimarySearch() {
// ...
}
Your logic is almost correct, you just need to use call() to provide the context for the function. Try this:
$('#primarySearch input[type="text"]').on({
"keyup": function(e) {
if (e.which != 9) {
processPrimarySearch.call(this);
}
}
});
function processPrimarySearch() {
// ...
}

Call keypress event on button click?

I have below jquery code which is execute on keypress but I would like to execute same on button click. Please help me.
$('#itemselected').live('keypress', function() {
//some code which using $(this) also.
}
var myFunction = function(event){
console.debug(event);
//do your stuff here
};
$('#itemselected').on('keypress', function(event) {
myFunction(event);
}
$('#itemselected').on('click', function(event) {
myFunction(event);
}
Try to trigger the keypress on click
$('button').click(function() {
$('#itemselected').trigger('keypress');
});
I think you can just add 'click' to the list of event types like so:
$('#itemselected').on('keypress click', function() {
//some code which using $(this) also.
});

How to better handle events

If I have multiple events on an element I am currently handling those events as written here:
$("body").on("click", ".element", function(e) {
// Do something on click
});
$("body").on("change", ".element", function(e) {
// Do something on change
});
Is there a way to combine all the events on an element in one on() call? What is the best practice if there are multiple events associated with one element?
$("body").on("change click", ".element", function(e) {
// Can I detect here if it was change or click event and perform an action accordingly?
});
You can use the type property of the event to determine which logic to execute:
$('body').on('change click', '.element', function(e) {
if (e.type == 'click') {
// do something...
}
else if (e.type == 'change') {
// do something else...
}
});
Alternatively you can provide an object to on which contains the functions to bind with the event type names as the keys:
$('body').on({
click: function() {
// do something on click...
},
change: function() {
// do something on change...
}
}, '.element');
Personally I would use the latter method. The whole point of having a unified on() handler is negated when using a rather ugly if statement to split the event types.
Yes! jQuery passes the event object which contain the event information:
$("body").on("change click", ".element", function(e) {
console.log(e.type);
});
You can use the event.type. Some will say it's bad practice and others may find it useful.
$("body").on("change click", ".element", function(event) {
switch (event.type) {
case 'click':
break;
case 'change':
break;
default:
}
});
jQuery event.type
$('#element').on('keyup keypress blur change', function(event) {
alert(event.type); // keyup OR keypress OR blur OR change
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="element" />

check multiple events - jQuery

Suppose I want to run a function myFunction at each of the events $(document).ready, $(sometag).on('click',....). How can I construct a function that checks if any of those two events are triggered, and then run the method. Can I pass $(document) as an argument and then check $(document).isReady or check $(document).click(function(e){if (e.target.is($(some tag))) ...}). Is this correct ?
It's not easy to understand what the heck you are talking about, but it sounds like you're trying to attach an event handler and trigger it on document ready, and if so you'd do that like this :
$(document).ready(function() {
$(sometag).on('click', function() {
// do stuff
}).trigger('click');
});
If I understand you correctly:
function myFunc(event) {
if (event.type == 'ready')
console.log('It is a document.ready');
else if (event.type == 'click')
console.log('It is a click');
}
$(document).on('ready', myFunc).on('click', 'a', myFunc);
jsfiddle
from what i could understand from your question...
Jsfiddle: http://jsfiddle.net/patelmilanb1/eR4wG/1/
$('.checkbox').change(function (e) {
if (e.isTrigger) {
alert('not a human');
} else {
alert("manual check by human");
}
});
$('.checkbox').trigger('change'); //alert not a human because it is automatically triggered.
I may not understand your question very much, but try this:
$(function(){
$('div1,div2,#id1,#id2,.class1,.class2').click(function(){
// do something
yourFunction();
});
});
triggering function on multiple events of an element, you may try:
$('#element').on('keyup keypress blur change', function() {
...
});
and multiple function on multiple elements, try:
$('#element #element1 #element2').on('keyup keypress blur change', function() {
...
});

jQuery event binding with accessibility in mind - click and keypress

Just a quick question, I seem to do this a lot:
$saveBtn.bind("click keypress", function(e)
{
if (e.type != "keypress" || e.keyCode == 13)
{
// Do something...
return false;
}
});
Is there a quicker way to bind an 'action' listener to a button? I want to always ensure my buttons with event listeners fire on both clicks and the enter key...this seems like it'd be a fairly common thing to want to do but found nothing on google. Any thoughts?
Thanks.
The click event doesn't actually handle the keypress in every case, it's the button that is making the click event work. When you use a div with a tabindex attribute to make it keyboard accessible, the click handler will not trigger when you press enter.
HTML
<div id="click-only" tabindex="0">Submit click only</div>
<div id="click-and-press" tabindex="0">Submit click and press</div>​
jQuery
$("#click-only").click(function (e) {
addToBody(); // Only works on click
});
$("#click-and-press").bind("click keypress", handleClickAndPress(function (e) {
addToBody(); // Works on click and keypress
}));
function addToBody() {
$("body").append($("<p/>").text("Submitted"));
}
function handleClickAndPress(myfunc) {
return function (e) {
if (e.type != "keypress" || e.keyCode == 13) {
myfunc(e);
}
};
}
So to answer the question, I don't think there is a better way (that works in every case) other than yoda2k's solution.
By binding it with click will do the job, no need for keep press. Example
You could create a second function which handles the additional logic and pass your function as a parameter:
function handleClickAndPress(myfunc)
{
return function (e) {
if (e.type != "keypress" || e.keyCode == 13) {
myfunc(e);
}
};
}
$saveBtn.bind("click keypress", handleClickAndPress(function (e) {
// do your stuff here
}));
If it's part of a form you could just listen for the "submit" event?

Categories

Resources