Home > Blockchain >  How can I loop this javascript function to remove redundant code?
How can I loop this javascript function to remove redundant code?

Time:02-26

I have multiple different divs that each represent an item. I am using data attributes to assign a start date and end date to each. Then I have a function written to check if the current date is within this range. If it is, then I have more code that will add display:block to each div. For each div I have a separate lines of code that I am trying to figure out how to rewrite so that it loops. I want to have as many divs (items) as needed without having to add new code for each specific one. What I have is functioning but very redundant and cumbersome to keep up with.

HTML:

<!--Class A-->
   <div id="Class-A"  data-class-start="1/1/2022" data-class-end="4/23/2022">
      <h1>Example</h1>
   </div>

<!--Class B-->
   <div id="Class-B"  data-class-start="2/1/2022" data-class-end="4/23/2022">
      <h1>Example</h1>
   </div>

<!--Class C-->
   <div id="Class-C"  data-class-start="3/1/2022" data-class-end="4/23/2022">
      <h1>Example</h1>
   </div>

JS:

/*--Class A--*/
var startA = document.getElementById("Class-A").getAttribute("data-class-start");
var endA = document.getElementById("Class-A").getAttribute("data-class-end");
if(dateCheck(startA, endA, new Date())) {
    document.getElementById("Class-A").style.display = "block";
  }

/*--Class B--*/
var startB = document.getElementById("Class-B").getAttribute("data-class-start");
var endB = document.getElementById("Class-B").getAttribute("data-class-end");
if(dateCheck(startB, endB, new Date())) {
    document.getElementById("Class-B").style.display = "block";
  }

/*--Class C--*/
var startC = document.getElementById("Class-C").getAttribute("data-class-start");
var endC = document.getElementById("Class-C").getAttribute("data-class-end");
if(dateCheck(startC, endC, new Date())) {
    document.getElementById("Class-C").style.display = "block";
  }

/*---Date Check Function--*/
function dateCheck(from,to,check) {

    var sDate,eDate,cDate;
    sDate = Date.parse(from);
    eDate = Date.parse(to);
    cDate = Date.parse(check);

    if((cDate <= eDate && cDate >= sDate)) {
        return true;
    }
    return false;
}

Thank you!

CodePudding user response:

Give them all a class in common - if col-12 isn't used elsewhere, you can use that. Then just iterate over all elements matching that class.

The third parameter doesn't come from information outside the function, so it isn't needed.

for (const elm of document.querySelectorAll('.col-12')) {
    if (dateCheck(elm.dataset.classStart, elm.dataset.classEnd)) {
        elm.style.display = 'block';
    }
}

function dateCheck(from, to) {
    const cDate = new Date();
    const sDate = Date.parse(from);
    const eDate = Date.parse(to);
    return cDate <= eDate && cDate >= sDate;
}
  • Related