Sergi Sergi - 1 month ago 18
Javascript Question

Applying DRY to a set of similar functions

Applying DRY is my biggest struggle. Can anyone help me create a single function that achieves the same as those 4 functions as well as how to call it for each .symbol?

$(".symbol:nth-child(1)").click(function(){
$("body").removeClass();
$("body").addClass("gradient1");
})


$(".symbol:nth-child(2)").click(function(){
$("body").removeClass();
$("body").addClass("gradient2");
})


$(".symbol:nth-child(3)").click(function(){
$("body").removeClass();
$("body").addClass("gradient3");
})


$(".symbol:nth-child(4)").click(function(){
$("body").removeClass();
$("body").addClass("gradient4");
})

Answer

You can create a function that takes an index and assigns a click handler:

function applyNthClick( n ) {
   $(".symbol:nth-child(" + n + ")").click(function(){
     $("body").removeClass();
     $("body").addClass("gradient" + n);
   })
}

And then use it like this:

applyNthClick(1);
applyNthClick(2);
applyNthClick(3);
applyNthClick(4);

Or, if you know all the ns, you could make an array of them, and then map the function over it:

[1,2,3,4].forEach( applyNthClick );