JavaScript
|
See also my page for: Programming |
| Webpages can really sparkle with JavaScript, an object-oriented,
event-driven, scripting language developed by Netscape. It can be used with HTML to make a page dynamic and
functional. On my website I use it to animate my buttons (see Image rollover) and
also to load images faster (see Preload images).
Don't confuse JavaScript with Java (see Danny Goodman article for quick explanation). They have some things in common but while JavaScript is a scripting language, Java is compiled, and much more robust. Mozilla.org explains the likeness between the languages this way, "The basic syntax is intentionally similar to both Java and C++ to reduce the number of new concepts required to learn the language." |
| Enabling JavaScript |
Some browsers have a setting to enable or disable JavaScript. If JavaScript is not enabled in your browser you
won't see my button animation, but with or without JavaScript enabled the buttons will still link to the intended
targets. Here is the location of this setting in several popular browsers.
|
| Top of page |
| In my job as web programmer I use a lot of JavaScript to enhance my Perl and HTML, and as I discover new things worth sharing I will add them here. I started developing this page years ago, before I was using JavaScript professionally, so some of the things offered here may be useful and functional while others may only seem clever and cute. |
Click this button to see image swapping in action:
This animation is produced from these 3 images:
The default image is Image 1, and it responds to mouse movements in the following ways:
One of the standards in 3D visual programming is that the source of light is from the upper-left, so the unpressed (protruding) button will have highlights on the top and left edges and shadows on the bottom and right, which you can see on Image 1. When the button is pressed, the shadows move to the top and left and the highlights move to the bottom and right, as in Image 3. To enhance the sense of movement when the button is clicked and the image is swapped, the text on the depressed button image is offset slightly. I use the highlighted image (Image 2) to catch the eye of the user when the mouse passes over it and show that it will receive focus by clicking the mouse. Besides being cute and flashy, the usefulness of this highlighting technique is more obvious in a menu setting, as in the column of buttons on my main page, where it helps in identifying which of the closely placed buttons will receive the mouse click.
Here is the code for the image swapping on this button.
// Preload the images to maximize performance image1 = new Image(100,20); image1.src = "image1.gif"; image2 = new Image(100,20); image2.src = "image2.gif"; image3 = new Image(100,20); image3.src = "image3.gif"; // Switch In, Out, and Highlight button images function imageSwap(imgID,imgName) { document.images[imgID].src = eval(imgName + ".src") } <!-- Call the image swapping function from the mouse events. --> <a href="target location here" onMouseOver ="imageSwap('mouse_test','image2')" onMouseDown = "imageSwap('mouse_test','image3')" onMouseUp = "imageSwap('mouse_test','image2')" onMouseOut = "imageSwap('mouse_test','image1')"> <img src="images/image1.gif" title="Click to test" name="mouse_test" width="100" height="20" border="0"></a>
Set it up this way on a page with lots of images.
// Put these in the <head> section background = new Image(); background.src = "myback.gif"; ... create objects with actual dimensions of images title = new Image(325,50); title.src = "titleimage.gif"; button1 = new Image(100,20); button1.src = "button1.gif"; button2 = new Image(100,20); button2.src = "button2gif"; button3 = new Image(100,20); button3.src = "button3.gif"; // Put these in the <body> section <img src="images/titleimage.gif" width="325" height="50"> <img src="images/button1.gif" width="100" height="20"> <img src="images/button2.gif" width="100" height="20"> <img src="images/button3.gif" width="100" height="20">
<table> <tr valign="middle"> <td> <a href="index.html" onMouseDown="imageSwap('home_btn','homeOn')" ...this goes on...
<table><tr valign="middle"><td><a href="index.html" onMouseDown="imageSwap('home_btn','homeOn')"...
document.write('<table><tr valign="middle"><td><a href="index.html" onMouseDown="imageSwap('home_btn','homeOn')"...')
document.write('<table><tr valign="middle"><td><a href="index.html" onMouseDown="imageSwap(\'home_btn\',\'homeOn\')"...')
<script language="JavaScript" type="text/javascript" src="header.js"></script>
Here is an example of how my webpages used to be constructed before removing the
header and footer source code.
![]()
Tips list
![]()
Here is the code for this example.
// Create the cookie with the text keyed into the form function setCookie(name) { var cookieText = document.myform.text.value; if (cookieText != "") { var today = new Date(); // Set the cookie to var oneYear = (1000 * 60 * 60 * 24 * 365); // expire in one var expDate = new Date(today.getTime() + oneYear); // year from today document.cookie=name + "=" + escape(cookieText) + "; expires=" + expDate.toGMTString(); document.myform.text.value = ""; // Clear the form } } // Retrieve the cookie text and display it in the form function getCookie(name) { var cookies = document.cookie.split("; "); // Get all cookies from file var cookieValue = " "; for (var i=0; i < cookies.length; i++) { values = cookies[i].split("="); // Extract cookie name & value if (values[0] == name) // If this cookie is found cookieValue = unescape(values[1]); // save the value } } document.myform.text.value = cookieValue; // Show cookie value on form } // "Delete" the cookie by expiring it function deleteCookie(name) { var today = new Date(); var expDate = new Date(today.getTime() - 1); document.cookie=name + "=; expires=" + expDate.toGMTString(); document.myform.text.value = ""; } // This goes in the <body> section <form name="myform"> Enter some text: <input type="text" name="text"> <input type="butto" value="Set cookie" onClick="setCookie('jscookie')"> <input type="button" value="Get cookie" onClick="getCookie('jscookie')"> <input type="button" value="Delete it" onClick="deleteCookie('jscookie')"> </form>
Showing today's date
You can obtain the current date and manipulate it using JavaScript.
![]()
The following code shows today's date as:
Showing the date a webpage was last changed<script type="text/javascript" language="JavaScript"> <!-- var today = new Date(); var yyyy = today.getYear(); if (yyyy < 1000) { yyyy += 1900; } var montharray=new Array("January","February","March","April","May","June","July", "August","September","October","November","December") var Month = montharray[today.getMonth()]; var dd = today.getDate(); document.write(Month + " " + dd + ", " + yyyy); // --> </script>
Using this property you can create a bookmark to see the date a webpage you are viewing was last changed.<script type="text/javascript" language="JavaScript"> <!-- update = new Date(document.lastModified) mm = update.getMonth() + 1 dd = update.getDate() yr = update.getYear() document.write(mm + "/" + dd + "/" + yr) // --> </script>
javascript:alert(document.lastModified)
var msgText = " ... Click the button again to clear this message ... " var msg = " " var delay = 150 var timerID = null var messageOn = false // Toggle between displaying or not-displaying message function msgFunction() { if (messageOn == false) { messageOn = true msg = msgText scrollMsg() } else { messageOn = false window.status = " " window.clearTimeout(timerID) } } // Scroll message by shifting leading character of message text to end of text function scrollMsg() { window.status = msg msg = msg.substring(1,msg.length) + msg.substring(0,1) // recursive call to this function timerID = setTimeout("scrollMsg()", delay) } <form> <input type = "button" value = "Press me" onClick = "msgFunction()"> and look at the message area at the bottom of the browser window... </form>
// Put this code in the <head> section function doBlink() { var blink = document.all.tags("blink") for (var i=0; i<blink.length; i++) blink[i].style.visibility = blink[i].style.visibility == "" ? "hidden" : "" } function startBlink() { if (document.all) setInterval("doBlink()",1000) } window.onload = startBlink(); // Put this where you want blinking text <blink>Some blinking text...</blink>
<input type="button" value="<< Back" onClick="history.go(-1)">
// Put this code in the <head> section function colorChoice(radiobutton) { var value = radiobutton.value; var bgColor = ''; // Define the background color corresponding to the clicked button if (value == "white") { bgColor = "#ffffff"; } else if (value == "green") { bgColor = "#66ffcc"; } else if (value == "red") { bgColor = "#ff3366"; } else if (value == "blue") { bgColor = "#99ccff"; } else if (value == "yellow") { bgColor = "#ffff99"; } // Change the color of the table cell radiobutton.parentNode.style.backgroundColor = bgColor; } // Put this code in the body section <form name="colorform"> <table border="2" cellpadding="5"> <tr> <td bgcolor="#ffffff"> White<input type="radio" name="colorbutton" value="white" onClick="javascript:colorChoice(this)" checked> Green<input type="radio" name="colorbutton" value="green" onClick="javascript:colorChoice(this)"> Red<input type="radio" name="colorbutton" value="red" onClick="javascript:colorChoice(this)"> Blue<input type="radio" name="colorbutton" value="blue" onClick="javascript:colorChoice(this)"> Yellow<input type="radio" name="colorbutton" value="yellow" onClick="javascript:colorChoice(this)"> </td> </tr> </table> </form>
| C H E C K B O X E S | R A D I O B U T T O N S |
|
// Put this code in the <head> section function clickCheckbox(checkbox) { if (checkbox.checked) { // Determine selection and unselect others var selected = checkbox.name; if (selected == "A") { checkboxform.B.checked = false; checkboxform.C.checked = false; } else if (selected == "B") { checkboxform.A.checked = false; checkboxform.C.checked = false; } else if (selected == "C") { checkboxform.A.checked = false; checkboxform.B.checked = false; } } } // Put this code in the body section <form name="checkboxform"> A <input type="checkbox" name="A" onClick="javascript:clickCheckbox(this)"> B <input type="checkbox" name="B" onClick="javascript:clickCheckbox(this)"> C <input type="checkbox" name="C" onClick="javascript:clickCheckbox(this)"> </form>
// This is with one line of code <a href="#tips" onClick="Javascript:return confirm('Are you sure this is what you want to do?')">Go to tips list</a> // This is using a function <a href="javascript:void(0)" onClick="return promptConfirm('Are you sure this is what you want to do?','#tips')">Go to tips list</a> function promptConfirm(question,href) { if (confirm(question)) { window.location = href; } }
// Create a form to input the message; the action, method, and onSubmit attributes are only used by the Enter key submit <form name="msgform" action="message_parm.html" method="get" onSubmit="return validateInput()"> Type in some text to display: <input type="text" name="msg" size="50"> <input type="button" value="Display message" onClick="validateInput();return false;"> </form> // Format a URL containing a '?msg=' parm function validateInput() { // Get the keyed in text from the form var msgtext = document.msgform.msg.value; if (!msgtext) { alert( 'Please enter some text.'); return false; } else { // Encode the message to allow it to contain spaces msgtext = escape(msgtext); // Get the path to the current page and format the new URL var thisurl = this.location.href; var spliturl = thisurl.split('js.html'); var newurl = spliturl[0] + "message_parm.html?msg=" + msgtext; // Display the new page window.location = newurl; } }
// Put function call in page load to extract parmed value <body onLoad="messageCheck(location.href)"> // Extract the message from the URL string function messageCheck(thisurl) { // Unencode the URL, which was encoded in my example to allow the message to contain spaces thisurl = unescape(thisurl); // Extract the message from the parm in the URL var spliturl = thisurl.split('?msg='); var msg = spliturl[1]; if (msg) { // Redisplay page without message parm in URL window.location = newurl[0]; // Display the message alert(msg); } }
// Put function call in page load to extract parmed value <body onLoad="getVideo(location.href)"> // Extract the video name from the URL string function getVideo(thisurl) { var spliturl = thisurl.split('?video='); var flv_file = spliturl[1]; // Format the <object> tag to play the video var content = '<object type="application/x-shockwave-flash" width="500" height="375" wmode="transparent" data="video/flvplayer.swf?file='; content = content + flv_file + '&autostart=true"><param name="movie" value="video/flvplayer.swf?file='; content = content + flv_file + '&autostart=true" /><param name="wmode" value="transparent" /></object>'; // Update the webpage with the new <object> tag document.getElementById('video').innerHTML = content; } // On the webpage... <div id="video"> </div>
// This function must run on page load (<body onload="formatText()>). function formatText() { var today = new Date(); var yyyy = today.getYear(); if (yyyy < 1000) { yyyy += 1900; } var montharray=new Array("January","February","March","April","May","June","July","August","September","October","November","December") var Month = montharray[today.getMonth()]; var dd = today.getDate(); document.getElementById('cnn_text').innerHTML = "Go to CNN.com on " + Month + " " + dd + ", " + yyyy; } // 'xxx' in this link will be replaced by the contents of cnn_text (text to be replaced cannot be null) <a href="http://www.cnn.com/" id="cnn_text">xxx</a>
Create a bookmark in your browser and call it something like Show tables. Copy & paste the following JavaScript into the URL property. When you click it you can see the table layouts on the current page in your browser.table { border: 1px solid red ! important; } table td { border: 1px dotted blue ! important; } table table { border: 1px solid green ! important; } table table td { border: 1px dotted green ! important; } table table table { border: 1px solid red ! important; } table table table td { border: 1px dotted orange ! important; } /* more deeply nested tables will also be red/orange */
| Original content |
![]()
// This function replaces the content with a parmed string function changeContent(webtext) { document.getElementById('change').innerHTML=webtext; } // Same as changeContent() without parm; handles extra quotes for image in string without syntax problems function changeContentImage() { document.getElementById('change').innerHTML='<img src="images/yinyang.gif" align=absmiddle> New text with icon...'; } <span id="change">Original content</span> <input type="button" value="Change text" onClick="changeContent('The text has changed...')"gt; <input type="button" value="Change content" onClick="changeContentImage()"> <input type="button" value="Reset" onClick="changeContent('Original content')">
// This class makes the text appear to be a clickable (underlined) link .fakelink {font-style: normal; font-weight: normal; color: #333399; text-decoration: underline;} // This class makes the text change color when the mouse hovers over it .fakehover {font-size: 100%; font-style: normal; font-weight: normal; color: #990033; text-decoration: none; background-color: transparent;} // This function, called on the mouseOver event, changes the color of the text and changes the shape of the mouse pointer to a hand (line a link would) function fakeHoverOn(text) { text.className = "fakehover"; document.body.style.cursor = 'pointer'; } // This function restores the look of a link (underlined text) when the mouse moves off the text and restores the shape of the mouse pointer function fakeHoverOff(text) { text.className = "fakelink"; document.body.style.cursor = 'default'; } // This function displays a message when the "link" is clicked on function noLinkMsg() { alert("Fooled you!\n\nEven though this looks like a link it is not!\n\n"); } // This is the "link" <span class="fakelink" onMouseOver="fakeHoverOn(this)" onMouseOut="fakeHoverOff(this)" onClick="noLinkMsg()">Test this fake link with the mouse</span>
// This function executes the menu selection function go_to_selection() { self.location.href = document.getElementById('dropdown').value; document.getElementById('dropdown').selectedIndex = 0; // reset to default for return to page } // This creates the drop-down menu <form id="menuform"> <select name="dropdown" onChange="go_to_selection()" style="width: 90px" class="drop_down"> <option selected value="">Sections...</option> <option value="#links">Links</option> <option value="#tips">Tips</option> <option value="#newsgroups">Newsgroups</option> </select> </form>
| Amazing Juggling Finale* | ||
| View of the World from 9th Avenue | ||
| The Zakim Bridge | ||
| Stanley Clarke - School Days* |
| On my website I like to show Flash videos in popups by generating webpages in Perl that embed a player. |
// This creates the window object and shows what is in the href argument function windowOpener(ref, target, parms) { popupWindow=window.open(ref, target, parms); popupWindow.focus(); } // Call the windowOpener function for the video example above <a href="video/AmazingJugglingFinale.swf" target="AmazingJuggling" onClick="javascript:windowOpener(this.href, this.target,'width=400,height=300,left=300,top=200,resizable=1');return false;">Amazing Juggling Finale</a> // Call the windowOpener function for the image example above <a href="images/ViewoftheWorldfrom9thAvenue.gif" target="NinthAvenue" onClick="javascript:windowOpener(this.href, this.target,'width=330,height=450,left=10,top=10');return false;">View of the World from 9th Avenue</a> // Call the windowOpener function for the webpage example above <a href="http://www.boston.com/traffic/bigdig/special/galleries/bridge/intro.htm" target="Zakim" onClick="javascript:windowOpener(this.href, this.target,'width=750,height=480,left=200,top=100');return false;">The Zakim Bridge</a> // Call the windowOpener function for the remote video example above (uses the FLV player on YouTube) <a href="http://www.youtube.com/v/KLIUj98rdXc" target="Clarke" onClick="javascript:windowOpener(this.href, this.target,'width=450,height=360,left=100,top=100,resizable=1');return false;">Stanley Clarke - School Days</a>
<form> Select a file: <input type="file" size="40"> [ fake submit button here in the example ] </form>
// The Ajax Javascript functions function getData(url) { // Create the XMLHttpRequest object if (window.XMLHttpRequest) { // Non-IE browsers http_request = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE http_request = new ActiveXObject("Microsoft.XMLHTTP"); } // Make the request http_request.onreadystatechange = processRequest; http_request.open('GET', url, true); http_request.send(null); } function processRequest() { if (http_request.readyState == 4) { if (http_request.status == 200) { // process the response after the server has completed the request var someXML = http_request.responseText; // the request expects XML to be returned, so you may want to parse it document.getElementById('PageContent').innerHTML = someXML; // change the content of the DIV } else { alert('There was a problem with the request.'); } } } // On the webpage... <input type="button" value="Get some data" onClick="getData('someURL')"> // value of 'someURL' could contain the name of a document or a script to run <div id="PageContent">The content of this section will be changed in the processRequest() function.</div>
// Call this function when the page loads function load_content() { var last_content = document.getElementById('cur_content').value; if (last_content == '') { replace_content('default-content'); // Load default content on initial display of page } else { replace_content(last_content); // If hidden variable has saved value redisplay this content } } function replace_content(request) { document.getElementById('cur_content').value = request; // Save request value to be detected by browser on next page load (...rest of replace_content function here...) } <body onLoad="load_content()"> <input type="hidden" id="cur_content" value="">
// Call this function when the page loads function start_here(thisurl) { // Extract perl script to run thisurl = unescape(thisurl); var spliturl = thisurl.split('?run='); var script = spliturl[1]; replace_content(script) } function replace_content(script_to_run) { if (window.XMLHttpRequest) { // Non-IE browsers http_request = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE http_request = new ActiveXObject("Microsoft.XMLHTTP"); } http_request.onreadystatechange = processRequest; http_request.open('GET', script_to_run, true); http_request.send(null); } function processRequest() { if (http_request.readyState == 4) { if (http_request.status == 200) { document.getElementById('PageContent').innerHTML = http_request.responseText; } } } // On the webpage... <body onLoad="start_here(location.href)"> <div id="PageContent">The content of this section will be changed in the processRequest() function.</div>
// Extract text into a variable
var variable-name = string-of-text.substring(starting-position,offset)
I had a task in a project where I work to emulate a check writing process, i.e. formatting the entered amount with punctuation and also creating a text version of the amount the way it is on a check.
JavaScript newsgroups
| I used to have several JavaScript usenet groups listed here but they don't seem to function in browsers anymore, so I am just providing a link to Google Groups, where they are offered in a web format. |
There are more newsgroups on my Programming page.