0

I have two elements. I have to do same code logic for one element's click and another element's change. How can I combine these two to avoid code duplication. I am looking for a solution other than calling a same function from both the events.

$( "element1" ).change(function(){
    //some stuff here
});

$( "element2" ).click(function(){
    //same above stuff here
});
2
  • 2
    Why not calling the same function? You could have $("element1").change(sharedFunction) and $("element2").click(sharedFunction) Commented May 21, 2017 at 17:44
  • 1
    Hey... I just noticed that: «I am looking for a solution other than calling a same function from both the events.»... What do you mean? Commented May 21, 2017 at 18:00

2 Answers 2

2

Put your "stuff" in an outer function...
Then call this function in your event handlers.

function myStuff(){
  //some stuff here
}


$( "element1" ).change(myStuff);

$( "element2" ).click(myStuff);
Sign up to request clarification or add additional context in comments.

2 Comments

@quirimmo: Thank for the edit... I approved it. ;) (I doesn't change anything... But it's more concise)
thanks :) yeah I just like to avoid inner functions when we can omit them :)
0

It's hard to say without knowing exactly what you're trying to do, but you could use the same callback function for each event.

var callback = function(e) {
  //shared functionality
}

$( "element1" ).change(callback);

$( "element2" ).click(callback);

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.