Reputation: 63
I have these two functions which have mostly similar code.. so I want to combine them into one function..
previousMonthImg.onclick = function() {
if (!(monthSelect.value === "Jan" && yearSelect.value === "2010")) {
monthSelect.selectedIndex--;
if (monthSelect.selectedIndex === -1) {
monthSelect.value = "Dec";
yearSelect.selectedIndex--;
}
}
triggerEvent(monthSelect, "change");
triggerEvent(yearSelect, "change");
};
nextMonthImg.onclick = function() {
if (!(monthSelect.value === "Dec" && yearSelect.value === "2030")) {
monthSelect.selectedIndex++;
if (monthSelect.selectedIndex === -1) {
monthSelect.value = "Jan";
yearSelect.selectedIndex++;
}
}
triggerEvent(monthSelect, "change");
triggerEvent(yearSelect, "change");
}
Upvotes: 0
Views: 64
Reputation: 3411
You can use this one:
const myNewFunc = (month, year, num) => {
if (!(monthSelect.value === month && yearSelect.value === year)) {
monthSelect.selectedIndex = monthSelect.selectedIndex + num;
if (monthSelect.selectedIndex === -1) {
monthSelect.value = month == 'Jan' ? 'Dec' : 'Jan';
yearSelect.selectedIndex = yearSelect.selectedIndex + num * -1;
}
}
triggerEvent(monthSelect, 'change');
triggerEvent(yearSelect, 'change');
}
nextMonthImg.addEventListener('click', () => {myNewFunc(...)})
previousMonthImg.addEventListener('click', () => {myNewFunc(...)})
Upvotes: 0
Reputation: 89234
You can use a function to create the event handler.
function makeHandler(monthEnd, monthStart, year, inc) {
return function(){
if (!(monthSelect.value === monthEnd && yearSelect.value === year)) {
monthSelect.selectedIndex += inc;
if (monthSelect.selectedIndex === -1) {
monthSelect.value = monthStart;
yearSelect.selectedIndex += inc;
}
}
triggerEvent(monthSelect, "change");
triggerEvent(yearSelect, "change");
}
};
previousMonthImg.onclick = makeHandler("Jan", "Dec", "2010", -1);
nextMonthImg.onclick = makeHandler("Dec", "Jan", "2030", 1);
Upvotes: 1
Reputation: 2104
You can combine both functions as below:
monthImg.onclick = function() {
let maxMonth = 0;
let minMonth = 0;
if (!(monthSelect.value === "Dec" && yearSelect.value === "2030")) {
maxMonth = 1;
}
if (!(monthSelect.value === "Jan" && yearSelect.value === "2010")) {
minMonth = 1;
}
if ((maxMonth) || (minMonth)) {
if (maxMonth) {
monthSelect.selectedIndex++;
} else {
monthSelect.selectedIndex--;
}
if (monthSelect.selectedIndex === -1) {
if (minMonth) {
monthSelect.value = "Jan";
yearSelect.selectedIndex++;
} else {
monthSelect.value = "Dec";
yearSelect.selectedIndex--;
}
}
}
triggerEvent(monthSelect, "change");
triggerEvent(yearSelect, "change");
}
But it will increase a bit complexity in the function. You can still keep them separated.
Upvotes: 0