Sergi Sergi - 1 year ago 91
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?





Answer Source

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

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

And then use it like this:


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 );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download