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(); update=copyright.getFullYear(); document.write("Copyright © 2011-"+ update); // End --> </script>
JavaScript uses // for one line comments or /* */ for one line or multiple line comments.
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>
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>
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):
<form>
<textarea name="myName" onkeypress="return limitText(this, 100);" ><textarea>
</form>
Shows current screen resolution.
<script type="text/javascript">
document.write(window.screen.width + ' x ' + window.screen.height); </script>
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"> document.write(document.lastModified); </script></p>
Which provides an output like this:
This page last updated: 10/18/2006 11:16:55
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:
Email: info@mysite.com
<script type="text/javascript">
<!-- Begin
user = "info";
domain = "mysite.com";
document.write('E-mail: <a href=\"mailto:' + user + '@' + domain + '\">' + user + '@' + domain + '</a>');
// End -->
</script>
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>