Leon
Leon

Reputation: 33

How to combine two jQuery functions

Good Morning.

I want to combine my jQuery functions into one.

$('body').on('click', '.toggle2', function() {
    console.log(123);
    $('body').find('.dateshow').toggleClass('show');

});

$('body').on('click', '.toogle3', function() {
    $('body').find('.autorshow').toggleClass('show');
});


$('body').on('click', '.toogle4', function() {
    console.log(123);
    $('body').find('.starshow').toggleClass('show');

});

Many thanks in advance

Upvotes: 1

Views: 476

Answers (3)

Jaromanda X
Jaromanda X

Reputation: 1

$('body').on('click', '.toggle2,.toogle3,.toogle4', function() {
    var mapper = {
        'toggle2': { cls: '.dateshow', console:true },
        'toggle3': { cls: '.autorshow', console:false },
        'toggle4': { cls: '.starshow', console:true }
    };
    this.classList.forEach(function(cls) {
        var obj = mapper[cls];
        if(obj) {
            obj.console && console.log(123);
            $('body').find(obj.cls).toggleClass('show');
        }
    });
});

Upvotes: 0

OK sure
OK sure

Reputation: 2646

If you change all of your toggle links to have the following markup:

<a href="#" class="toggle" data-toggle="dateshow">click</a>
<a href="#" class="toggle" data-toggle="autorshow">click</a>
<a href="#" class="toggle" data-toggle="starshow">click</a>

Then you can add a more generic handler such as:

$('.toggle').on('click', function() {
     var targetSelector = $(this).attr('data-toggle');
     $('.' + targetSelector).toggleClass('show');
});

Codepen: http://codepen.io/anon/pen/aBKJEb

Upvotes: 6

Richard Parnaby-King
Richard Parnaby-King

Reputation: 14862

When a callback is called jQuery will pass in an event object. You can check the target of the event and process as needed.

$('body').on('click', '.toggle2, .toogle3, .toogle4', function(e) {
    var $target = jQuery(e.target),
        $targetObject;

    if($target.hasClass('toggle2')) {
        $targetObject = jQuery('body').find('.dateshow');
    }
    if($target.hasClass('toogle3') {
        $targetObject = jQuery('body').find('.autorshow');
    }
    if($target.hasClass('toogle4') {
        $targetObject = jQuery('body').find('.starshow');
    }

    $targetObject.toggleClass('show');
});

Upvotes: 2

Related Questions