supersaiyan
supersaiyan

Reputation: 1730

merge two function which have same property

I have two function which have same property. But I don't know how to merge in a one consolidate function and I tired to google it but don't know what exactly the keyword for this

$test  = $('.slider .pager li.slide1 a'),
$test1 = $('.slider .pagination li a')

$test.bind('click', function(e) {
    e.preventDefault();
    sliderHandler.slideFirst();
    alert("1");
});

 $test1.bind('click', function(e) {
    e.preventDefault();
    sliderHandler.slideFirst();
});

Its working fine for me. But I just want to make it more smaller and nice.

Upvotes: 0

Views: 56

Answers (3)

Rok Burgar
Rok Burgar

Reputation: 949

$test        =   $('.slider li a');

$test.click(function(e) {
    e.preventDefault();
    sliderHandler.slideFirst();
    if ($(this).parent().hasClass('slide1'))
        alert("1");
});

Upvotes: 0

Khanh TO
Khanh TO

Reputation: 48982

Why don't try?

$test = $('.slider .pager li.slide1 a,.slider .pagination li a'),

$test.bind('click', function(e) {
    e.preventDefault();
    sliderHandler.slideFirst();
    alert("1");
});

In your case, just update the selector to select all elements that you need to apply the same logic.

Update: If they are global variables already, we can try merging them:

$.merge( $.merge( [], $test), $test1).bind('click', function(e) {
    e.preventDefault();
    sliderHandler.slideFirst();
});

As pointed out by @doubleswirve in the answer below, we could also use add instead of merge: $test.add($test1).bind('click'

Upvotes: 2

doubleswirve
doubleswirve

Reputation: 1428

What about using the jQuery .add method (similar to @Khanh TO's answer):

// Assuming these have already been declared
$test  = $('.slider .pager li.slide1 a');
$test1 = $('.slider .pagination li a');

$test.add($test1).bind('click', function(e) {
  e.preventDefault();
  sliderHandler.slideFirst();
  alert("1");
});

Here's a CodePen demonstrating a similar example.

Upvotes: 1

Related Questions