Showing content based on the current date using Javascript

Although I may not be proficient in Javascript, I was able to gather examples and piece together the following code:

    var date = new Date().getDate();  
    var greeting;

    if (date < 24) {
        greeting = "Nej det är:";
    } else {
        greeting = "Ja!";
        document.getElementById("clockdiv").style.visibility = "hidden";
    }

    document.getElementById("demo").innerHTML = greeting;

The code is intended to display a specific greeting based on the current date, with an alternative greeting if it's not the specified date.

There are a few issues with the code:

  1. If the date exceeds (e.g., 24), it triggers errors;
  2. It only considers the day, overlooking the month;
  3. There are also some minor errors present.

Answer №1

From what I gathered, you were referring to the specific day of the month.

Here's the code snippet on Js fiddle: https://jsfiddle.net/tscm02xb/

const currentDate = new Date();
const dayOfMonth = currentDate.getUTCDate();

let message;
if (dayOfMonth < 24) {
    message = "No, it is:";
} else {
    message = "Yes!";
    document.getElementById("clockdiv").style.visibility = "hidden";
}
document.getElementById("demo").innerHTML = message;

Answer №2

The function Date().getDate() retrieves only the day of the month. You can experiment with this code snippet.

let date = new Date();  
let greeting;

if (!(date.getDate() === 24 && date.getMonth() === 11)) {
    greeting = "No, it's:";
} else {
    greeting = "Yes!";
    document.getElementById("clockdiv").style.visibility = "hidden";
}

document.getElementById("demo").innerHTML = greeting;

Answer №3

Here is a helpful code snippet:

let currentDate = new Date();
let day = currentDate.getDate();
let month = currentDate.getMonth();
let message;
if (day !== 24) {
    message = "No, it is not the 24th.";
} else if (day === 24 && month === 0) { // This should be January
    message = "Yes!";
    document.getElementById("clockdiv").style.visibility = "hidden";
}
document.getElementById("response").innerHTML = message;

Answer №4

I want to express my gratitude for all the helpful responses. I synthesized them all and arrived at a solution. Allow me to share it with you. Check out the code snippet on JsFiddle: https://jsfiddle.net/linushg111/o6u8quwz/

    var date = new Date();  
   var day = date.getDate();
   var n = date.getMonth();
   var greeting;
    if (day === 24 && n === 11) {
        greeting = "YES";
    } else {
        greeting = "NO :-(";
    }
document.getElementById("demo").innerHTML = greeting;

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

Trigger a JavaScript function upon clicking a link

Is it possible to have a CMS that loads articles using ajax, where the article is loaded through a function with parameters, and when a certain link is clicked, it redirects to the target page and launches the function on that page? For instance, let' ...

Is it possible to trigger an event each time an Ajax request is made within AngularJS?

I am looking for a way to automatically display a spinner with a dark overlay every time a call is made to the backend. While I know I can manually implement this by triggering the spinner before each call, I prefer a solution that does not require addit ...

Are Bootstrap Input groups inconsistent?

Hey there! I've been working on the sign-in example, but I seem to have hit a roadblock. In my local setup, the top image is what I see in my browser after running the code, while the desired layout that I found on the Bootstrap site is the one below ...

Experience the power of Vue Google Chart - Geochart where the chart refreshes seamlessly with data updates, although the legend seems to disappear

I have integrated vue google charts into my nuxt project. Whenever I select a different date, the data gets updated and the computed method in my geochart component correctly reads the new data. However, the legend or color bar at the bottom does not funct ...

Top tip: Utilize jQuery for the most effective method of adding content to the HTML of a paragraph situated

One interesting challenge I'm facing involves a textarea that stores dynamic HTML content within paragraph (p) tags. Initial HTML: <textarea rows='7' class='form-control' id='comments'><p>My variable HTM ...

Converting HTML content into a single string simplifies data manipulation and extraction

exampleHTML=" This is sample HTML code that needs to be converted into a string using JavaScript </p>" I am looking to transform it into a single string format like str="This is sample HTML code, that needs to be converted into a string ...

Access another page by clicking on a link within an HTML document

Is it possible to include an anchor tag in demo1.html that, when clicked, will take the user to the demo2.html page and automatically select a data filter on that page? Here is the code snippet for demo1.html: <li> <div><a href="urunli ...

JQuery Submission with Multiple Forms

Hey everyone! I have a jQuery form with multiple fieldsets that switch between each other using jQuery. Eventually, it leads to a submit button. Can someone assist me by editing my jfiddle or providing code on how I can submit this data using JavaScript, j ...

Utilize images inputted via an HTML DOM file uploader within p5.js

I'm facing a challenge with allowing users to upload their image file through a DOM file uploader (<input type="file"></input>). Once the image is uploaded, I'm unsure of how to transfer it to JavaScript and process it using p5.js. Ho ...

Encountering a Material UI error: Incorrect hook usage when combining create-react-library with MUI

After transitioning from Material Ui v3 to v4 on a create-react-library project, I encountered an issue. This particular project serves as a dependency for other projects in order to share components. However, when attempting to display a material-ui compo ...

Being required to design a distinct div for every article I am extracting from the API

In the midst of developing a website for my college project, I have successfully configured my news API to pull and display data using JavaScript. Currently, I am faced with the challenge of having to create separate div elements each time I want to add n ...

Linking chained functions for reuse of code in react-redux through mapStateToProps and mapDispatchToProps

Imagine I have two connected Redux components. The first component is a simple todo loading and display container, with functions passed to connect(): mapStateToProps reads todos from the Redux state, and mapDispatchToProps requests the latest list of todo ...

retrieve information using Python in JavaScript

I am in the process of developing a website using Python, Javascript (JQuery), and AJAX. While I know how to initiate a Python script with Ajax, I am unsure of how to send data back to Javascript from Python. For instance, if there is an error in a form s ...

Capturing Data from Tables and Saving it with Protractor

Imagine having a table structured like this <h2>HTML Table</h2> <table> <tr> <th>Company</th> <th>Contact</th> <th>Code</th> </tr> <tr> <td>Alfreds Fu ...

The act of transmitting data via a timer using JS WebRTC leads to crashes if the page is reloaded before

In one of my server.js files served by a node, I have written the following code snippet: function multiStep(myConnection, data) { var i=0; var myTimer=setInterval(function() { if (i<data.length){ var element=JSON.string ...

The Dropdown Button Functions Once and Then Stops

I am facing a challenge in implementing a button within an HTML table that triggers a dropdown menu when clicked, and closes upon another click or when the user clicks outside the menu. Oddly, the button only seems to work once before completely losing fun ...

How can we display or conceal text indicating the age of a patient based on the value returned from selectedPatient.age in a React application?

Hello, I am looking to dynamically display the age in years on the screen based on the value retrieved from selectedPatient.age, toggling between visible and hidden states. import React, { useContext } from 'react'; import { useHistory } from &ap ...

Javascript: object continuously moving despite key being released

When I leave the keyword new on line: var myGamePiece = new makeComponent(myContext, 30, 30, "red", 10, 120); The red square continues to move even when I release the arrow key. However, if I remove the new element from that line, the square stops moving ...

Retrieve the observable value and store it in a variable within my Angular 13 component

Incorporating Angular 13, my service contains the following observable: private _user = new BehaviorSubject<ApplicationUser | null>(null); user$ = this._user.asObservable(); The ApplicationUser model is defined as: export interface ...

Switching from an AJAX GET request to a POST request involves updating the

I have been trying to figure out how to convert my AJAX GET query to POST by reading forums and searching on Google, but I am still confused. If someone could assist me with this, it would be greatly appreciated. Thank you! Here is the code snippet I am w ...