How can I use Moment.js to show a custom message based on the current day of the week?

Currently, I am utilizing Moment.js to dynamically showcase various messages based on the day of the week.

For instance, if it's:

  • If it's Monday, I want it to display "It's Monday!"
  • If it's Tuesday, I'd like it to show "Happy Tuesday!"

This is what I have so far: moment().format('dddd'), which accurately shows the current day of the week. However, I'm unsure how to implement different messages based on each specific day.

Thank you in advance for taking the time to assist with this query.

Ollie

Answer №1

Identifying the current day is a simple task, even without relying on moment.js:

console.log("Happy " + ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"][new Date().getUTCDay()-1])

Here's a more intricate example below:

var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
var day = new Date().getUTCDay() - 1;

function getDayMessage() {
  switch (day) {
    case 0:
      return "Moody " + days[day];
      break;
    case 1:
      return "Trippy " + days[day];
      break;
    case 2:
      return "Weeping " + days[day];
      break;
    case 3:
      return "Thundering " + days[day];
      break;
    case 4:
      return "Freaky " + days[day];
      break;
    case 5:
      return "Salty " + days[day];
      break;
    case 6:
      return "Super " + days[day];
      break;
    default:
      return "Happy " + days[day];
  }
}

var classes = document.getElementById("messageOfTheDay").getAttribute('class').split(' ');
classes.push('day-' + days[day].toLowerCase());
document.getElementById("messageOfTheDay").setAttribute('class', classes.join(' '))
document.getElementById("messageOfTheDay").innerHTML = getDayMessage();

console.log("Below is the HTML code for or `h1`. Notice the added day-{DAY-OF-WEEK}");
console.log(document.getElementById("messageOfTheDay"));
<h1 id="messageOfTheDay" class="hello world"></h1>

The previous snippet has been updated to a function that returns the string. Now you can easily choose to alert, console.log, or insert it into your page as I did above.

Answer №2

If you're looking for a way to handle different days of the week, one approach could be using a switch case statement:

var message = '';

switch (moment().format('dddd')) {
                case 'Monday':
                    {
                        message = 'Happy Monday!';
                        break;
                    }
                case 'Tuesday':
                    {
                        message = 'Enjoy your Tuesday!';
                        break;
                    }
                    // Add more cases as needed
            }

document.getElementById('daily-message').innerHTML = message;
<div id='daily-message'></div>

Answer №3

Consider attempting something similar:

if(moment().format('dddd') == "Wednesday")
    //try this
if(moment().format('dddd') == "Thursday")
    //try that instead

Answer №4

Take a look at this example. Utilize the myMessage variable as necessary

let myMessage = '';
switch(moment().format('dddd')){
    case 'Monday':
        myMessage = "Hello Monday!";
        break;
    case 'Tuesday':
        myMessage = "Terrific Tuesday!";
        break;
    case ...
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it beneficial to utilize components in order to streamline lengthy HTML code, regardless of whether the components do not repeat and do not require any props (such as in Vue or any other JavaScript library

In the Vue.js team project I am currently involved in, I have structured my code in the view as follows: component01 component02 ... There are more than 10 components in total. Each component represents a section of the landing page, consisting mostl ...

What steps do I need to take in order to implement a functional pagination menu in Vue?

I downloaded and installed laravel-vue-pagination with the following command: npm install laravel-vue-pagination After that, I globally registered it in my app.js file: Vue.component('pagination', require('laravel-vue-pagination')); F ...

Tips for including an additional label on a data point within a scatter plot using the Highcharts JavaScript framework

Incorporating the Highcharts JavaScript library, I am visualizing float values by passing them from PHP to the JS code. In the image below, you can observe that upon hovering over each point, the corresponding axes values are displayed along with the text ...

Despite being initialized previously in JavaScript, the attribute of the object is still showing as undefined

After using an attribute from an Object multiple times, it suddenly appears as undefined when I call it in another function. Even though I have checked its values with console.log and they seem to be assigned correctly. Can anyone help me figure out what I ...

Leveraging data stored in a parent component within a child component in Vue.js

Working with Laravel Spark, I have implemented a component within another component. <parent-component :user="user"> <child-component :user="user" :questions="questions"></child-component> <parent-component> Inside the parent ...

Guide on separating a variable by commas using jQuery

After making an Ajax call to a Java servlet, I am retrieving data and storing it in the 'data' variable upon success. Here is the code snippet: var s1=""; var ticks =""; $('#view').click(function(evt ...

Straining data in text input fields using bootstrap

Looking for a way to filter data with bootstrap/jquery without using tables, just div rows and columns. Check out an example of how my form looks Here's a snippet of my code: <div class="row"> <div class="col-md-4"> <input class= ...

Adding objects to an existing array in Vue.js can be a seamless and

Struggling to populate my existing array with elements from a JSON response using a button click. The issue lies in properly adding these elements to the array. I have an empty array named results where I store the data from the response. export default ...

Unlocking the API endpoints within nested arrays in a React project

{ [ "quicktype_id": 1, "quicktype": "Laptops", "qucik_details": [ { "type_name": "car", "type_img": "car_img" }, { "type_name": "van", "type_img": ...

Error encountered: The use of 'import' and 'export' is limited to 'sourceType: module' when attempting to install Tweakpane

I am currently learning JavaScript and have been following a course on Domestika that requires me to install the Tweakpane package. I usually use Git Bash for installing packages, and I have successfully installed others this way before. Here is the proces ...

Are there alternative methods to retrieve the CSS properties of web elements more effectively than relying on selenium?

I have a situation in my code where I need to retrieve the CSS properties of a large number of web elements. Currently, I am using Selenium and the code looks like this: ... node = browser.find_element_by_xpath(xpath_to_node) return {k: node.v ...

Javascript textfield button function malfunctioning

Here is the code I have created: HTML: <form method="post" id="myemailform" name="myemailform" action="form-to-email.php"> <div id="form_container"> <label class="descriptio ...

Creating a React button animation with CSS vibes

When I click a button, I want a subtle sparkle to appear and disappear quickly, within half a second. I've thought about using a gif, but it requires a lot of manual artistic work to achieve the desired effect. Is there a way to utilize the Animatio ...

Tips for accessing the current state/value in a third-party event handler?

Consider the following scenario: function MapControl() { const [countries, setCountries] = useContext(CountriesContext) useEffect( () => { ThirdPartyApi.OnSelectCountry((country) => { setCountries([...countries, country]) }) }) ...

When an image is added, it will display against a backdrop of pure white

Hey there, I have a question regarding an image on my website. I removed the background using PowerPoint, but when I upload it, there is still a white background around it. Even changing the background color doesn't remove the white outline. Any tips ...

Is it possible to send arguments to a debounced function using _.lodash?

Utilizing _lodash.debounce() has been a bit of a challenge for me. While I have managed to get it working, I can't help but feel that there might be a better way to implement it. The examples provided on the lodash website are quite basic and don&apos ...

What is the solution for aligning <grid> containers to match the height of the tallest container in the row?

I've been grappling with a CSS issue. I'm attempting to ensure that my accordion containers within my layout all have the same height as the tallest item on their respective rows. This would create a sleek and responsive layout where all items ar ...

Utilizing a JavaScript class within the document ready function

Having trouble with a countdown script wrapped as an object in a separate file. Struggling to setup multiple counters or objects due to the timeout function in the countdown class not finding the object that was set up within the document ready event. Wh ...

Error: The module 'cropbox' could not be located. 2

I posed the inquiry Module not found: Error: Can't resolve 'cropbox' Unfortunately, I did not receive a response, prompting me to delve into more specific issues and scour StackOverflow for solutions. After investigating, I identified thr ...

Unable to delete product from shopping cart within React Redux reducer

Currently, I am tackling the challenge of fixing a bug in the shopping cart feature of an e-commerce website I'm working on. The issue lies with the remove functionality not functioning as expected. Within the state, there are cartItems that can be ad ...