Silly question but suppose I wanted to change the fonts based on a condition. As a silly example, perhaps something like changing all the fonts on my website to Comic Sans on April Fool's. How can I achieve that?
For this example, I know how to get the date and most other conditions, but I can't figure out how to change the font family in body
based on the result.
Some ideas:
- Add a class with its own font choosing to override the font family.
- Make the default fonts a variable and change it to a new font family if the condition is met.
I'm not too familiar with DOM, so if anyone with more experience could help answer, that would be great. Do any of these ideas work, and if so, how can I implement them? Thanks!
CodePudding user response:
You can get the current date as a Date object by initializing the Date object: new Date()
, you can then compare the month and date with the target date, e.g. 1st of April.
Then you can assign an inline font-family style to the body.
const today = new Date();
if(today.getMonth() == 03 && today.getDate() == 01)
document.body.style.fontFamily = `"Comic Sans MS", sans-serif`;
Hello world!
Alternatively, you can assign a class to it by using document.body.classList.add("april-fools");
which would add .april-fools.
You can test the target date by initializing the date object with "01 April", e.g:
new Date("01 April")
to see the result as if it's the 1st of April.
const today = new Date("01 April");
if(today.getMonth() == 03 && today.getDate() == 01)
document.body.style.fontFamily = `"Comic Sans MS", sans-serif`;
Hello world!
CodePudding user response:
You can create a class for each font, and with javascript
apply this font on some specific date
.font1 {
font-family: ...
}
.font2 {
font-family: ...
}
function setClassOnAprilFirst() {
var currentDate = new Date();
var currentMonth = currentDate.getMonth();
var currentDay = currentDate.getDate();
if (currentMonth == 3 && currentDay == 1) {
document.getElementById("getBody").classList.add("font1");
}
}
CodePudding user response:
Try the below code :
- In your CSS file, define the font family for the body element:
body { font-family: Arial, sans-serif; }
In your JavaScript file, define a function that will change the font family based on a condition:
function changeFontFamily(condition) { if (condition) { document.body.style.fontFamily = "Verdana, sans-serif"; } else { document.body.style.fontFamily = "Arial, sans-serif"; } }
Call the changeFontFamily() function and pass in the condition as an argument:
changeFontFamily(true);