RMaxwell87
RMaxwell87

Reputation: 119

Javascript If statement HTML

I have the following code to generate the current date in a specific format. I want to have an if statement that will change the back ground color and the font color depending if the specific day is on a Sunday, Saturday, or a Week day.

var date = new Date();
var dayMonthYear = date.toLocaleString('en-US', {month:'long',day:'numeric',year:'numeric'}).replaceAll(", ", "-");
var weekday = date.toLocaleString('en-US', { weekday: 'long' })
document.write(dayMonthYear + ' [' + weekday + ']');

I thought I would just create a general if statement that looks at the weekday variable but it doesn't seem to work correctly like I would think.

if (weekday = 'Sunday') {
    background-color:aqua;
    color: blue;
    }

Also, any ideas on how to get a - between the Month and Day number?
Example: August-15-2021 My current code generates August 15-2021

Upvotes: 0

Views: 132

Answers (2)

ahsan
ahsan

Reputation: 1504

A good approach to this would be to make your preferred stylings as different classes then add that class to your HTML using JavaScript.

That way you can avoid the if statements altogether

I have made an applyStyling function that takes the weekday variable as an argument

function applyStyling(day){
  let body = document.querySelector("body");
  body.classList.add(day.toLowerCase());
}

var date = new Date();
var dayMonthYear = date.toLocaleString('en-US', {month:'long',day:'numeric',year:'numeric'}).replaceAll(", ", "-");
var weekday = date.toLocaleString('en-US', { weekday: 'long' })
document.write(dayMonthYear + ' [' + weekday + ']');

applyStyling(weekday);
.sunday {
  background-color:aqua;
  color: blue;
}
.monday {
  background-color:lightcoral;
  color: brown;
}

Upvotes: 2

vanowm
vanowm

Reputation: 10201

Single = is assigning value to the variable, while double == or triple === is a comparison between two values.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators

Once you corrected the expression, the actual color change of a HTML element can be done via inline style:

element.style.backgroundColor = "aqua";

or better yet by changing/adding css class of the element:

element.classList.add("aqua");

As for adding - you can use this regex / (\d)/

var date = new Date();
var dayMonthYear = date.toLocaleString('en-US', {month:'long',day:'numeric',year:'numeric'}).replaceAll(", ", "-");
var weekday = date.toLocaleString('en-US', { weekday: 'long' })

console.log(dayMonthYear.replace(/ (\d)/, '-$1') + ' [' + weekday + ']');

if (weekday == 'Sunday') {
  document.body.style.backgroundColor = "aqua";
  document.body.style.color = "blue";
}

document.body.classList.add("myclass");
body.myclass
{
  font-size: 10em;
}
test

Upvotes: 1

Related Questions