Search code examples
javascriptdom-eventsdry

Javascript events - how to make this code DRY


I'm learning JavaScript. Can somebody help me to make this code DRY (don't repeat yourself) please? The code is about changing color of paragraph by clicking on particular connected-with button. I have no idea how to make the changeColor function applicable for particular block of code without making a new version of this function.

var greenPar = document.getElementById("green-paragraph");
var greenColorBtn = document.getElementById("greenColorBtn");
var redPar = document.getElementById("red-paragraph");
var redColorBtn = document.getElementById("redColorBtn");
greenColorBtn.addEventListener("click", changeColorGreen);
redColorBtn.addEventListener("click", changeColorRed);

function changeColorGreen() {
    if (greenPar.className == "") {
        greenPar.className = "green"; //.green{ color:green;}
    } else {
        greenPar.className = "";
    }
}

function changeColorRed() {
    if (redPar.className == "") {
        redPar.className = "red"; //.red{ color:red;}
    } else {
        redPar.className = "";
    }
}

Solution

  • Use common function as click handler and pass color value as argument.

    As you will be using this value in handler, use Function#bind and pass this-context, second argument will be color value to be compared.

    var greenPar = document.getElementById("green-paragraph");
    var greenColorBtn = document.getElementById("greenColorBtn");
    
    var redPar = document.getElementById("red-paragraph");
    var redColorBtn = document.getElementById("redColorBtn");
    
    greenColorBtn.addEventListener("click", changeColor.bind(greenColorBtn, 'green'));
    redColorBtn.addEventListener("click", changeColor.bind(redColorBtn, 'red'));
    
    function changeColor(color) {
      var thisElem = this;
      if (thisElem.className == "") {
        thisElem.className = color;
      } else {
        thisElem.className = "";
      }
    }