Mishen Thakshana
Mishen Thakshana

Reputation: 143

Doing the same function with Multiple click events in jquery

$(document).on('click','#closeNewProductExpand', function() {

        $('#newProductExpand').css('width', '0');
    });

    $(document).on('click', '#searchProduct', function() {

        $('#newProductExpand').css('width', '0');
    });

    $(document).on('click', '#productsData', function() {

        $('#newProductExpand').css('width', '0');
    });

Here I want to set the width to 0 of #newProductExpand if one of the above 3 buttons is clicked.Is there any way to write this code rather than wasting such a larger space.I appreciate your help.Thanks

Upvotes: 0

Views: 37

Answers (2)

I_love_vegetables
I_love_vegetables

Reputation: 1341

You can give the elements a class and simply target the class to make it easier instead of targeting the element IDs one by one.

Like this:

$('.className').click(function(){
   $('#newProductExpand').css('width', '0');         
});

Upvotes: 1

Barmar
Barmar

Reputation: 780974

you can combine selectors with comma.

$(document).on('click','#closeNewProductExpand, #searchProduct, #productsData', function() {
    $('#newProductExpand').css('width', '0');
});

However, as an alternative I suggest you give all these elements a common class, and use that as the selector. That way, if you need to add more elements to the set, you just give them the same class, you don't need to make the list of selectors longer every time.

Upvotes: 2

Related Questions