1

I have the following finctions in my script and they do the same thing. How may I combine them?

$('.AddOne').live('click', function(){
    $('.saveGroup').show();
});
$('#PhoneNumbersSelectms2side__sx  option').dblclick(function(){
    $('.saveGroup').show();
});
$('.AddAll').live('click', function(){
    $('.saveGroup').show();
});

1 Answer 1

4

The click and dblclick event methods each take a callback function as their first argument. In javascript functions are variables. you create a function, and pass it to the callbacks

var showFn = function(){
    $('.saveGroup').show();
};

$('.AddOne').live('click', showFn);
$('#PhoneNumbersSelectms2side__sx  option').dblclick(showFn);
$('.AddAll').live('click', showFn);

You can further simplify this code by combining the live selectors like this:

$('.AddOne, .AddAll').live('click', showFn);

Finally, if you are using jquery 1.7.x you should use the new on event methods instead of live. Your new code would look like this:

var showFn = function(){
    $('.saveGroup').show();
};
var $doc = $(document);
$doc.on('click', '.AddOne, .AddAll', showFn);
$doc.on('dblclick', '#PhoneNumbersSelectms2side__sx  option', showFn);
Sign up to request clarification or add additional context in comments.

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.