1

I'm trying to find a way of writing some sort of function so that I don't have to keep rewriting the same type of code.

As you can see below, both blocks of code are pretty much the same except one is for the lunchTimeSelector and the other is for the napTimeSelector? Is there any way to write a function so that I can just automate this by just inputting an array like [lunchTimeSelector, napTimeSelector, dinnerTimeSelector], etc. into a function to replace this code?

// Activates Lunch selector
var lunchTimeSelector =  document.getElementById("lunchTimeSelector");

var lunchEvent = function()
{
    lunchtime = lunchTimeSelector.value;
};

lunchTimeSelector.addEventListener("change", lunchEvent);





// Activates Nap-Time selector
var napTimeSelector =  document.getElementById("napTimeSelector");

var napEvent = function()
{
    naptime = napTimeSelector.value;
};

napTimeSelector.addEventListener("change", napEvent);
2
  • Think about a function where you will pass element id Commented Jul 6, 2020 at 3:35
  • Suggest you develop it a bit more with those two so we can better see what they are intended to do with their respective values. Then a more generic approach can be developed not just for setting separate event listeners but for whatever processing you do with those variables as well Commented Jul 6, 2020 at 3:42

2 Answers 2

1

You could implement it like so:

function addChangeEvent(id, handler){
    document.getElementById(id).addEventListener("change", handler);
}
[["lunchTimeSelector", function(){lunchtime = this.value}], 
 ["napTimeSelector", function(){naptime = this.value}]]
    .forEach(([id,handler])=>addChangeEvent(id,handler));
Sign up to request clarification or add additional context in comments.

Comments

0

maybe you can try :

// wrap all your logic 
function lanuchNapTimeSelector(id,state){

 var target =  document.getElementById(id);

// your handelers
 var lunchEvent = function()
 {
    lunchtime = target.value;
 };

 var napEvent = function()
 {
    naptime = target.value;
 };

 target.addEventListener("change", state === "nap" ? napEvent : 
 lunchEvent);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.