2

I have the following code ..

$("#input_name").blur(function(){
  //more code
});

It works fine, but now I need to invoke the same functionality as in the blur function above by clicking a button as well. Basically, I want to keep the blur as is, and add the onclick. Any ideas how do I do that? Thanks

3 Answers 3

8

You can do this:

$("#input_name").bind("blur click", function() { ... });

You can also separate the function definition from the binding:

function handler() { ... }

$('#input_name').blur(handler).click(handler);

Remember that jQuery will pass the event to the handler function, and you can check the event type:

function handler(ev) {
  if (ev.type === 'click') { ... }
Sign up to request clarification or add additional context in comments.

5 Comments

Just a quick q - $('#input_name').blur(handler).click(handler); does this invoke the code twice??
That doesn't invoke the code at all - it has the same effect as calling "bind" once with both event names really. Those functions call the already-bound handlers when you call them with no parameters, but when you pass in a function it just wires it up for future events. Make sense?
Hmm .. to be honest, it just went over the head. Anyway, I appreciate your help. Cheers.
Oh I just realised the bind above is for blur and click on the input itself .. actually my question was to have 2 different elements calling same function. and Joekari has answered it right
Well then if that's the case, you'd use the second approach. Declare the function, and then bind it to as many elements as you want.
4

Change your function definition to not be inline and then reuse it.

function eventFunction(){
    //more code
}

$('#input_name').blur(eventFunction);
$('#button_name').click(eventFunction);

3 Comments

Any ideas how do I prevent default event? I know I can use event.preventDefault(); but not sure what is the best position to use it? Will it be ok inside eventFunction? I am not sure as I am using the blur as well ?
by passing in the event object to the function, you can manipulate it. function eventFunction(e){//code} you can call prevent default at any time, and if you want to keep the event from bubbling you can return false from your event function.
see @pointy's answer about the event type also. Then you can determine which parent function was called.
1

Place "//more code" in a function:

function more_code() {
    //more code
}

and call it from your handlers:

$("#input_name").blur(more_code)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.