0

I am very new to JS I just created my very first web app but I am having trouble tidying up my code.

My HTML has 3 range sliders I take the value from each and change the color of the thumb depending on that value (RAG). It works fine the way I have implemented it but I have repeated myself quite a bit.

document.getElementById(complex).addEventListener("change", complexityFunction);
document.getElementById(uncert).addEventListener("change", uncertaintyFunction);
document.getElementById(repeat).addEventListener("change", repetitionFunction);

function complexityFunction() {
  var x = document.getElementById(complex).value;
  if (x == 1) {
      this.className = "green";
  } else if (x == 2) {
      this.className = "amber";
      } else {
          this.className = "red"
      }
  }

function uncertaintyFunction() {
  var x = document.getElementById(uncert).value;
  if (x == 1) {
      this.className = "green";
  } else if (x == 2) {
      this.className = "amber";
      } else {
          this.className = "red"
      }
  }

function repetitionFunction() {
var x = document.getElementById(repeat).value;
if (x == 1) {
    this.className = "green";
} else if (x == 2) {
    this.className = "amber";
    } else {
        this.className = "red"
    }
}

Here's what I have tried (amongst other things) which hasn't worked!:

document.getElementById(complex).addEventListener("change", assessmentFunction(complex));
document.getElementById(uncert).addEventListener("change", assessmentFunction(uncert));
document.getElementById(repeat).addEventListener("change", assessmentFunction(repeat));

function assessmentFunction(argument) {
  var x = document.getElementById(argument).value;
  if (x == 1) {
      this.className = "green";
  } else if (x == 2) {
      this.className = "amber";
      } else {
          this.className = "red"
      }
  }

Can somebody please help me out?

  • 1
    The usual thing is a wrapper function: `document.getElementById(complex).addEventListener("change", () => assessmentFunction(complex));` Note that that will use the value of the `complex` variable as it is when the event occurs. If you want to use the value as it is when you hook up the handler, you can do that with `bind` instead: `document.getElementById(complex).addEventListener("change", assessmentFunction.bind(undefined, complex));` – T.J. Crowder Dec 19 '21 at 12:23
  • This hasn't worked for me. The complex variable never changes, it's just a placeholder for the string "complexity". – Stacey Harvey Dec 19 '21 at 12:32
  • Sorry, didn't notice you were using `this` in `assessmentFunction`, which changes things a bit: `document.getElementById(complex).addEventListener("change", function() { assessmentFunction.call(this, complex); });` – T.J. Crowder Dec 19 '21 at 12:46
  • 1
    You're a genius! Thank you so much, it worked! – Stacey Harvey Dec 19 '21 at 12:49

0 Answers0