Why this Display Current Month and Year with Data Attributes Script is useful

  • Automatically displays the current month and year without manual updates.
  • Handles missing elements gracefully, avoiding JavaScript errors.
  • Lightweight and easy to integrate into any webpage.
  • Display Current Month and Year with Data Attributes Script

    Here’s the JavaScript you’ll need to include in your webpage:

    How to Use It

    1. Add the Script to Your PageCopy and paste the above script into a <script> tag at the bottom of your HTML file, right before the closing </body> tag, or include it as an external JavaScript file.

    Example: 

    <script src="path/to/your/script.js"></script>

    2. Add HTML Markup Add elements to your HTML where you want the month and year to appear. Use the attributes data-date="year" and data-date="month".

    Example: 

    <p>The current year is: <span data-date="year"></span></p>
    <p>The current month is: <span data-date="month"></span></p>

    3. Test Your Page

    • Open your webpage in a browser.
    • Verify that the year and/or month appears in the appropriate locations.

    What Happens If an Element is Missing?

    If either the data-date="year" or data-date="month" element is missing, the script will log a message to the browser console instead of throwing an error. This ensures the rest of your page and scripts remain unaffected.

    Example Use Case

    You might use this script for:

    1. Displaying the current year in a footer for copyright purposes:

    <footer>© <span data-date="year"></span> My Website</footer>

    2. Adding a dynamic date to a blog or article header:

    <header>Published in <span data-date="month"></span>, <span data-date="year"></span></header>
    

    Benefits of using this script

  • Automatically displays the current month and year without manual updates.
  • Handles missing elements gracefully, avoiding JavaScript errors.
  • Lightweight and easy to integrate into any webpage.
  • Feel free to copy and adapt this solution for your projects.