samair ali
samair ali

Reputation: 802

Is there any way to change color after every 7 days after specific date?

I want to change color of div after every 7 days. I have tried changing it using if statements but I want more specific way of doing it (automatically after 7 days add color).

This is what I tried:

     <div class="hello">
    checking

</div>
<script>
    var currentDate = new Date().getDate()
        console.log(currentDate)
        var hello = document.querySelector(".hello")
        function getMondays() {
            var d = new Date(),
                month = d.getMonth(),
                mondays = [];
            d.setDate(1);
            // Get the first Monday in the month
            while (d.getDay() !== 1) {
                d.setDate(d.getDate() + 1);
            }

            // Get all the other Mondays in the month
            while (d.getMonth() === month) {
              console.log(new Date(d.getTime()))
                mondays.push(new Date(d.getTime()));
                d.setDate(d.getDate() + 7);
            }
            console.log(mondays)

            if(mondays.length === 4 ){
                hello.setAttribute("alt","")
                hello.removeAttribute("src")
                console.log("in 4")
              if(currentDate > 0 && currentDate < mondays[0].getDate()){
                  hello.style.backgroundColor = "orange"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
              if(currentDate >= mondays[0].getDate() && currentDate < mondays[1].getDate()  ){              
                  hello.style.backgroundColor = "green"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
              if(currentDate >= mondays[1].getDate() && currentDate < mondays[2].getDate()  ){              
                  hello.style.backgroundColor = "purple"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
              if(currentDate >= mondays[2].getDate() && currentDate < mondays[3].getDate()  ){              
                  hello.style.backgroundColor = "blue"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
              if(currentDate >= mondays[3].getDate() && currentDate <= 31  ){              
                  hello.style.backgroundColor = "orange"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
            }
            if(mondays.length === 5 ){
              console.log("in 5")
              if(currentDate > 0 && currentDate < mondays[0].getDate()){
                  hello.style.backgroundColor = "orange"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
              if(currentDate >= mondays[0].getDate() && currentDate < mondays[1].getDate()  ){              
                  hello.style.backgroundColor = "green"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
              if(currentDate >= mondays[1].getDate() && currentDate < mondays[2].getDate()  ){              
                  hello.style.backgroundColor = "purple"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
              if(currentDate >= mondays[2].getDate() && currentDate < mondays[3].getDate()  ){              
                  hello.style.backgroundColor = "blue"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
              if(currentDate >= mondays[3].getDate() && currentDate < mondays[4].getDate()   ){              
                  hello.style.backgroundColor = "orange"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
              if(currentDate >= mondays[4].getDate() && currentDate <= 31  ){              
                  hello.style.backgroundColor = "green"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
            }
        }
        getMondays()
   </script>

in this code I am taking Mondays of the current month and adding color one by one. And I want to add 4 colors.

The issue is when we have 5 weeks: then it will not loop accordingly.

Upvotes: 0

Views: 543

Answers (3)

Paul
Paul

Reputation: 2076

You could calculate the current week number and use it for setting the color.

const containerEl = document.getElementById('container');
const containerEl2 = document.getElementById('container2');
const containerEl3 = document.getElementById('container3');
const containerEl4 = document.getElementById('container4');
const weekClassPrefix = "week-"

// source https://www.w3resource.com/javascript-exercises/javascript-date-exercise-24.php
let isoWeekNumber = function(dt) {
  let tdt = new Date(dt.valueOf());
  let dayn = (dt.getDay() + 6) % 7;
  tdt.setDate(tdt.getDate() - dayn + 3);
  let firstThursday = tdt.valueOf();
  tdt.setMonth(0, 1);
  if (tdt.getDay() !== 4) {
    tdt.setMonth(0, 1 + ((4 - tdt.getDay()) + 7) % 7);
  }
  return 1 + Math.ceil((firstThursday - tdt) / (60 * 60 * 24 * 7 * 1000));
}

let setBackgroundColor = function(date, element) {
  let weekNo = isoWeekNumber(date);
  // NOTE: I use % 4 to ensure it's between 0 and 3. If you want more variance colors, 
  // just set the number to the number of colors and add the classes to the css.
  // I recommend to put all styles in there as long as there is no real need to do it via js.
  element.classList.add(weekClassPrefix + (weekNo % 4));
  
  // For debugging only.
  element.innerHTML = date.toLocaleDateString("en-GB", { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
}

let setCurrentBackgroundColor = function() {
  setBackgroundColor(new Date(), containerEl);
}

setCurrentBackgroundColor();
setBackgroundColor(new Date("2020-05-31"), containerEl2);
setBackgroundColor(new Date("2020-06-01"), containerEl3);
setBackgroundColor(new Date("2020-06-08"), containerEl4);
#container, #container2, #container3, #container4 {
  width: auto;
  height: 28px;
  padding: 10px;
  color: white;
}

.week-0 {
  background-color: orange;
}

.week-1 {
  background-color: green;
}

.week-2 {
  background-color: purple;
}

.week-3 {
  background-color: blue;
}
<div id="container">
</div>

<div id="container2">
</div>

<div id="container3">
</div>

<div id="container4">
</div>

Upvotes: 1

Kishin Karra
Kishin Karra

Reputation: 140

Something on these lines? I think it has bugs but it should give you a gist.

// Get a date
const date = new Date();
// Todays date ex: 30
const numDate = date.getDate();
// Todays day of week: sunday = 0;monday = 1; so on
const numDay = date.getDay();
// Go to sunday
date.setDate(numDate - numDay);

const weekNum = Math.floor(date.getDate() / 7);

const colors = ["Red", "blue", "green", "orange", "pink"]
const todaysColor = colors[weekNum]

Here is the codepen: https://codepen.io/kishin-karra/pen/yLYmYvE Have updated the codepen as well

Upvotes: 2

CoderDesu
CoderDesu

Reputation: 885

You can use timer for this. Your html:

<div class="block"></div>

Your css:

.block {
  width: 100px;
  height: 100px;
  background-color: green;
}

And the most important. Your javascript:

const block = document.querySelector(".block");
const dayInMs = 24 * 60 * 60 * 1000;
const delay = dayInMs * 7;
const colorSet = ["blue", "green", "red"];
let colorIndex = 0;

setTimeout(changeColor, delay);

function changeColor() {
  if (colorIndex === colorSet.length) {
    colorIndex = 0;
  }
  block.style["background-color"] = colorSet[colorIndex];
  colorIndex++;
  setTimeout(changeColor, delay);
}

Steps: 1.Get access to your DOM-element 2.Define a quantity of milliseconds in a days, since setTimeout works with milliseconds. 3.Define some color set in array or set, or another composite data-structure 4.Call a recursive timer, that every delay time will call changeColor function.

P.S. You can try setInterval, but recursive setTimeout is more reliable.

Here is codepen (you can change delay for another value, not to wait for 7 days :D): https://codepen.io/evgeny-zubkov/pen/qBOeOxe?editors=1111

Upvotes: 0

Related Questions