Reusable function actions?

javascript
jquery

#1

In this example:

$('input').click(function () {
    $(this).parent().css('opacity', '1').prev().css('opacity', '1').find('input').attr('disabled', 'disabled');
});

I want everything after $(this) to be reusable so I can apply those same actions to any id I specify later in my code without having to do something like this:

$("#thisGroup").click(function () {
        $("#group1").parent().parent().css('opacity', '.5').prev().css('opacity', '.5').find('input').attr('disabled', 'disabled');
        $("#group2").parent().parent().css('opacity', '.5').prev().css('opacity', '.5').find('input').attr('disabled', 'disabled');
});
$("#thatGroup").click(function () {
        $("#group3").parent().parent().css('opacity', '.5').prev().css('opacity', '.5').find('input').attr('disabled', 'disabled');
        $("#group4").parent().parent().css('opacity', '.5').prev().css('opacity', '.5').find('input').attr('disabled', 'disabled');
});

What is the best and cleanest way to do this?
Javascript or jQuery answers are fine :slight_smile:


#2

Make it a function with a parameter taking the element in question(please do give it a more meaningful name that “doTheThing” :smile: )

 doTheThing = function (element) {
    $(element).parent().parent().css('opacity', '.5').prev().css('opacity', '.5').find('input').attr('disabled', 'disabled');
};

$("#thisGroup").click(function () {
    doTheThing("#group1");
    doTheThing("#group2");
});
$("#thatGroup").click(function () {
    doTheThing("#group3");
    doTheThing("#group4");
});

You can of course go more fancy and make functions that return those click actions for lists of groups you want them to work on etc.
(note: I haven’t tested this code)


#3

Thanks @SephDB. I’ll try it out tomorrow morning. Thank you!