1

I'm messing about with JavaScript/jQuery, and just trying to determine how to refactor two very similar:

 $('#a-div-element').click(function() {
    /* common stuff in here */
})

into one function with two arguments. I'd expected it to be somewhat similar to other languages I've used, that is:

function my_refactored_stuff(field, target_div) {
  $(field).click(function{ 
    /* common stuff in here */
  });
}

But that doesn't seem to trigger when clicked

In short, if someone could do up a quick example of how to write up a function that handles common functionality across .click methods, I'd be really appreciative

Many thanks, PlankTon

1
  • At the moment, it's the actual element, eg $('#my-element') Commented Sep 11, 2012 at 1:21

2 Answers 2

2
var callback = function() {};

$('#a-div-element').click( callback );

Or if you wish to pass arguments:

$('#a-div-element').click(function() {
    callback( /* args */ );
});
Sign up to request clarification or add additional context in comments.

Comments

2

Just define and re-use an event handler function.

var handler = function(event) { /* common stuff here */ }
$("#a-div-element").on("click", handler)
$("#b-div-element").on("click", handler)

2 Comments

Looks promising, but how do I pass in arguments?
You don't pass arguments to an event handler; the argument is always the DOM event object. What kinds of arguments are you wanting to pass? If you need custom behavior per element, then you will need a custom function per handled event, but you can move common functionality into a separate function if needed.

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.