user2465422
user2465422

Reputation: 157

jQuery function in two events

I have this code:

$('#email').keyup(function() {
            if(true || false)) {

            } else {

            }
        });

I need include this function also in blur event.

I've tried to create a jquery function but I could not. Somebody give me a light.

Upvotes: 1

Views: 80

Answers (4)

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

Use the on method to attach multiple events, which are specified in the first argument passed to the function.

$('#email').on('keyup blur', function() {
    if(true || false) {  //there was an extra ) here

    } else {

    }
});

Working Example http://jsfiddle.net/nv39M/

One thing to be aware of, the keyup event is going to fire prior to the blur event firing.

Upvotes: 2

gaurav
gaurav

Reputation: 128

Make a separate function as follows

function funcName(){
//Your code
}

Now,use jQuery on

 $("#email").on("keyup",funcName);
 $("#email").on("blur",funcName);

For reference,check

http://api.jquery.com/on/

Upvotes: 1

Anthony Grist
Anthony Grist

Reputation: 38345

There are (at least) two ways you could achieve this.

  1. Specify multiple, space separated events as the first argument:

    $('#email').on('keyup blur',function() {
        // your logic
    });
    
  2. Use a named function:

    function yourFunction() {
        // your logic
    }
    
    $('#email').on('keyup', yourFunction);
    $('#email').on('blur', yourFunction);
    

Option 1 is probably the best choice assuming you don't want to use the function anywhere else, and that you want to bind the event handlers at the same time. If, however, you wanted to bind the blur event at a later point (perhaps in response to another event), or to a different element, then the named function method would be the best choice.

Upvotes: 1

Adil Shaikh
Adil Shaikh

Reputation: 44740

You can do this -

$('#email').on('keyup blur',function() {

Upvotes: 5

Related Questions