skip to Main Content

I’m trying to make a schedule to change who is doing a task every 7 days. I need it to change a html element class and repeat every Friday. Thanks in Advance.

var date = new Date();
  var dayOfWeek = Date.getDay(); // 0 is Sunday, 1 is Monday, etc...
  var kestrals = document.getElementById("k");
  var eagles = document.getElementById("e");
  var merlins = document.getElementById("m");
  var currentDuty
  var intervalID = window.setInterval(changeDuty, 10000);

  function changeDuty() {
    if(dayOfWeek=5) {
        //Dont know what do do here
    }

  }

2

Answers


  1. One solution might be to use the classList property of the element.

    Example:

    const kestrals = document.getElementById("k");
    const eagles = document.getElementById("e");
    const merlins = document.getElementById("m");
    
    let currentDuty = kestrals; // initial duty value
    
    function changeDuty() {
      const today = new Date();
      const dayOfWeek = today.getDay(); // 0 is Sunday, 1 is Monday, etc.
    
      if (dayOfWeek === 5) { // 5 - Friday
        switch (currentDuty) {
          case kestrals:
            toggleDuty(kestrals, eagles);
            currentDuty = eagles;
            break;
          case eagles:
            toggleDuty(eagles, merlins);
            currentDuty = merlins;
            break;
          case merlins:
            toggleDuty(merlins, kestrals);
            currentDuty = kestrals;
            break;
          default:
            toggleDuty(kestrals, eagles);
            currentDuty = eagles;
            break;
        }
      }
    }
    
    // toggle duty class on elements
    function toggleDuty(offDuty, onDuty) {
      offDuty.classList.remove("duty");
      onDuty.classList.add("duty");
    }
    
    // set the initial value of the duty class for the element
    kestrals.classList.add("duty");
    
    // call changeDuty() every week
    const oneWeek = 7 * 24 * 60 * 60 * 1000;
    const intervalID = setInterval(changeDuty, oneWeek);
    Login or Signup to reply.
  2. There are many issues with your code and you underestimate the complexity of that task.
    I will not tell you everything you have done wrong but start over with that task from scratch.

    First of all, you must understand how Javascript works. JavaScript is client-sided and runs within the browser. This means that JS will run if a website or web application is called and continues until the website is closed.

    Your task is, that on Friday the name on duty changes. Let’s assume you open the website at Thursday 11:59 pm. Then Kestrel would be on duty. One minute later, the duty changes. So you need your functions to run at a small time frame over and over again to keep up to date. If as @4efirrr suggested running check only every 7 days, then the update of the duty will happen next week at 11:59 pm when actually the next group is only for one more minute on duty. If you check every second, then you put too much load on the browser and the PC which is unnecessary.

    However, the main issue with that is, that it assumes that the website/web application is open and running 24/7. The website or application is not allowed to be ever closed!

    Why?
    let’s assume Eagels is on duty. What will happen if you close the application and re-open it? Then the script will start over from the start and Kestrel would be shown on duty.

    The easiest way to solve the issue is by checking the current week’s number of the year. What you can do with that function:

    let currentDate = new Date();
    let startDate = new Date(currentDate.getFullYear(), 0, 1);
    let days = Math.floor((currentDate - startDate) / (24 * 60 * 60 * 1000));
    let weekNumber = Math.ceil(days / 7);
    

    To update the duty on every Friday you can use an if statement that checks if it is Friday or later in the week. It will cause an issue on Sunday as it has the number 0 which is smaller and not higher than 5. SO you need to add an or within the condition. If that condition is true, you simply add 1 to the week’s number to change the duty early:

    if (dayOfWeek >= 5 || dayOfWeek === 0) {
      weekNumber++;
    }
    

    When you have the week number you can use a simple division: week's number / amount of names and take the remainder (% in programming). With that remainder, you can pick the correct name from the list of all names such as:

    const names = ['kestral', 'eagles', 'merlins'];
    
    let currentDutyIndex = weekNumber % names.length;
    let currentDuty = names[currentDutyIndex];
    

    Then you remove the class duty from all elements and add it to the element that should be on duty by using the classList + add()/remove() methods.

    const NAMES = ['kestral', 'eagles', 'merlins'];
    
    window.addEventListener('DOMContentLoaded', changeDuty); //checks if the document has been parsed
    window.setInterval(changeDuty, 60000); //checks if the day and the duty has changed every 1 minute
    
    function changeDuty() {
      // running a function to get the current week number of the year
      let weekNumber = getWeek();
      
      // selects the name from the array which is on duty
      let currentDutyIndex = weekNumber % NAMES.length;
      let currentDuty = NAMES[currentDutyIndex]; 
      
      // removes the class "duty" from all elements
      document.querySelectorAll('.duty').forEach(el => el.classList.remove('duty'));
      
      // adds the class "duty" to the correct element
      document.querySelector(`#${currentDuty.charAt(0)}`).classList.add('duty');
    }
    
    
    function getWeek() {
      let currentDate = new Date();
      let startDate = new Date(currentDate.getFullYear(), 0, 1);
      let days = Math.floor((currentDate - startDate) / (24 * 60 * 60 * 1000));
      let weekNumber = Math.ceil(days / 7);
      
      // swapping to the next week if the day is friday or later
      let dayOfWeek = currentDate.getDay();
      if (dayOfWeek >= 5 || dayOfWeek === 0) { //checks if the current day is friday or later incl. sunday
        weekNumber++;
      }
      
      return (weekNumber);
    }
    .duty {
      background-color: yellow;
    }
    <div id="k">Kestrel</div>
    <div id="e">Eagles</div>
    <div id="m">Merlins</div>

    PS: I highly advise you not to use id names such as k, e, and m. It is a bad habit and poor coding. In fact, in most companies, it is a requirement (convention) to use ids and names that speak for themself. This allows others to easily read and understand your code and as such makes maintenance easier. which results in shorter maintenance times. Maintenance time is working time and as such costs wages/salary. So you have economic reasons to make ids, classes, variables, and constants names longer in return for readability, maintenance, and lower costs.

    Another thing I changed which is also important for productive use is scalability. @4efirrr had hardcoded everything. That will cost a complete overhaul if a name changes or names are added/deleted. Good code will not care for the exact names nor how many names exist. In my example, you can simple add or remove names within the array and it will still work correctly.WHich again comes back to the above mentioned economic point. If a program needs to be overhauled to adjust for changes then it cost time and money. Adding or removing or changing a name within an array is a matter of seconds.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search