Smartlab Software logo

JavaScript Snippets

Here are some helpful JavaScript snippets. Most only show the salient points for brevity sake.


Show this year in YYYY format.

<script type="text/javascript">
<!-- Begin
copyright=new Date();
document.write("Copyright &copy; 2011-"+ update);
// End -->

avaScript Comments

JavaScript uses // for one line comments or /*  */ for one line or multiple line comments.

Embed JavaScript

Always put the JavaScript between the <head> tags so it is processed before the page loads. Note the HTML comments around the JavaScript. This is to prevent older browsers from displaying the JavaScript.

<script type="text/javascript">
document.write(window.screen.width + ' x ' + window.screen.height);
--> </script>

External JavaScript File

Always put the JavaScript reference between the <head> tags. The first time the external JavaScript file is referenced it is downloaded from the server; subsequent references load the file from cache.

<script type="text/javascript" src="jsfile.js"></script>

Limit Number of Characters in a Textarea in a Form

The <textarea> tag in a form has no way of limiting the number of characters typed in. The maxlength attribute only works in the single line <text> tag. Test it out with a small number, like 15.

JavaScript function for limiting number of chars entered:

function limitText(limitField, limitNum)
    if (limitField.value.length > limitNum)
        limitField.value = limitField.value.substring(0, limitNum);

Here is how it is implemented in a form (this example has a 100 character limit):

<textarea name="myName" onkeypress="return limitText(this, 100);" ><textarea>


Shows current screen resolution.

<script type="text/javascript"> 
document.write(window.screen.width + ' x ' + window.screen.height); </script>

Last Modified Date

Note that JavaScript last modified code will only accurately report the date for static HTML/XHTML pages and not those with dynamically generated content.

To create a last modified date for your web page in EWD to replace the FrontPage webbot you can use the following as a code snippet:

<p>This page last updated: 
  <script type="text/javascript">

Which provides an output like this:

This page last updated: 10/18/2006 11:16:55

Hide Email from Spambots

This JavaScript is for providing a clickable email address but hides the email address from spambots.
Put anywhere on your page between <body> and </body>. This will generate a line that looks like:


<script type="text/javascript">
<!-- Begin
 user = "info";
 domain = "";
 document.write('E-mail: <a href=\"mailto:' + user + '@' + domain + '\">' + user + '@' + domain + '</a>');
// End -->

Properly Code a Back Button

Add this to the back button JavaScript code. This works even if the visitor came from a different website.

onclick="history.back();return false;"
<a href="javascript:history.back()">Back</a>