I’m going to show you how to automatically update the copyright year of your website without the use of PHP. I have been seeing a lot of posts about, how to update the copyright notice of your website using PHP’s date() function. What about those people whose websites are not PHP Diven?

Well, you can do something very similar using JavaScript. All you need is access to your HTML files.

Writing the Display Copyright Function

We are going to write a Javascript function that will output Copyright © [current year]. Where [current year] is … you guessed it, the current year.

<script type="text/javascript">
//<![CDATA[
/**
 * Function looks for element whose id is copyright and
 * inserts a dynamic copyright notice with the current year
 */
	function DisplayCopyright(){
		var d = new Date();
		var e = document.getElementById("copyright");
		e.innerHTML = ("Copyright © " + d.getFullYear());
}
 //]]>
</script>

  • This function instantiates a Date object.
  • Looks for the element whose id is equal to copyright.
  • Inserts a dynamic copyright notice with the current year, according to local time.

Placing the Copyright Element

Now that we have the function that is going to dynamically generate the copyright notice. We need to add the element which will hold the copyright notice.

I’ll use a <span> element.

<span id="copyright"> </span>

You may place the above, wherever you want the copyright notice to be displayed.

Making it Work

Now that we have all of the separate pieces, it’s time to make it all function together. You are going to need to call the DisplayCopyright function we have created earlier. One way to do this is by placing an window.onload following the function.

<script type="text/javascript">
//<![CDATA[
/**
 * Function looks for element whose id is copyright and
 * inserts a dynamic copyright notice with the current year
 */
	function DisplayCopyright(){
		var d = new Date();
		var e = document.getElementById("copyright");
		e.innerHTML = ("Copyright © " + d.getFullYear());
}
//call DisplayCopyright when page finishes loading
window.onload = DisplayCopyright;
 //]]>
</script>

There you have it, a non PHP way of dynamically updating the copyright notice of your website. Keep in mind that if the user browser has JavaScript disabled, this particular solution will not work.

Related Posts