Skip to content Skip to sidebar Skip to footer

How To Combine Keypress & On Click Function In Javascript?

I have the following two functions: $('input').keypress(function(event) { if (event.which == 13) { //code } }); $('#login_submit').click(function () {

Solution 1:

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);

Solution 2:

Add a class to your HTML

<input class="myClass">
<divid="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.

Solution 3:

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.

Solution 4:

I would chain the events like:

var watchCurrentCursorPosition = function (){
            console.log("foo");
        }
        $("input").keypress(
            watchCurrentCursorPosition

        ).click(
            watchCurrentCursorPosition
        );

Solution 5:

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        
  }       
});

Post a Comment for "How To Combine Keypress & On Click Function In Javascript?"