Dynamic Current Year

Writes the current year into every element with the data-current-year attribute using Date.getFullYear(). Use a placeholder like 20?? so the intended behaviour is clear before JavaScript runs.

yearcopyrightjavascriptdynamicfooter
Dynamic Current Year preview

Code

index.html
html
<p>© <span data-current-year="">20??</span> Osmo</p>
script.js
javascript
function initDynamicCurrentYear() {
  const currentYear = new Date().getFullYear();
  const currentYearElements = document.querySelectorAll('[data-current-year]');
  currentYearElements.forEach(currentYearElement => {
    currentYearElement.textContent = currentYear;
  });
}

// Initialize Dynamic Current Year
document.addEventListener('DOMContentLoaded', () => {
  initDynamicCurrentYear();
});

Guide

data-current-year

Add to any element where the current year should appear. All matching elements on the page are updated at once, so you can place it in multiple locations (e.g. footer copyright and a legal page).

Placeholder

Set the element's initial text to a placeholder like 20?? so the intended dynamic value is visible in the CMS editor or before JavaScript runs.