Reputation: 3079
Hi,
I have 2 functions that do the exact same thing:
$("#submitmsg").click(function () {
sendmessage();
});
///second function
$("#usermsg").keypress(function(e) {
if (e.which == 13) {
console.log(e.shiftKey ? 'Shift & Enter' : 'Enter only')
if (!e.shiftKey) {
sendmessage();
}
}
});
I want to save as much code as possible so I would prefer something like "if this function OR this function". Something like this:
if $("#submitmsg").click || $("#usermsg").keypress(13) && !13.shiftKey {
sendmessage();
}
but I cant get the syntax right. How is it done?
Thank you.
Upvotes: 1
Views: 50
Reputation: 51711
You can remove the anonymous function as your click
handler as it's doing nothing more than passing the call to sendmessage()
. Just pass the sendmessage
function reference directly as
$("#submitmsg").click(sendmessage);
Your second function cannot be combined with the first one as both the id
selectors as well as the triggering events are different. But, you could slim it down to
$("#usermsg").keypress(e => {
if (e.which == 13 && !e.shiftKey)
sendmessage();
});
unless the console.log
call is important to you.
Upvotes: 1
Reputation: 171679
What you were probably wanting to try is combining multiple events with the same handler.
I don't think that is practical in the scenario shown since you have different selectors also and some conditional logic in one of the cases.
A very simple example of doing it with same selectors that checks the event.type
is as follows:
$('#test').on('focus input', function(e){
console.log(`Event type= ${e.type}`);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="test" placeholder="edit me"/>
Upvotes: 0