js 中出现这个个问题Cannot read readwritepropertyy 'style' of undefined

TABLE OF CONTENTS
Read &&, before trying out these examples. At a minimum, you should have the &Firebug& (or Web Developer Tools). It is very difficult to debug JavaScript codes due to its loose syntax. One misspell character in variable or function name, may waste a lot of your time, as JavaScript treat it as a new item or abort the function.
It is a good practice to separate the HTML contents, CSS presentation styles and JavaScript behavior programming codes in three different files, &.html&, &.css& and &.js&, for ease of maintenance and good software engineering practice. The now-preferred approach is not to embed styles and JavaScript codes inside HTML document, but keep them in separate files.
[TODO] More examples on jQuery + HTML5/CSS3
HTML Form Input Validation
NOTE: HTML5 supports form input validation. You should use HTML5 for input validation, which is much simpler and stable (Read &&). On the other hand, there are also tons of advanced Form Input Validator libraries, such as Parsley JS.
Using HTML5
HTML &H5FormValidation.html&
&!DOCTYPE html&
&html lang=&en&&
&meta charset=&utf-8&&
&title&HTML Form Input Validation Using HTML5&/title&
&h2&HTML Form Input Validation Using HTML5&/h2&
&form id=&formTest& method=&get& action=&processData&&
&td&&label for=&txtName&&Name&span class=&required&&*&/span&&/label&&/td&
&td&&input type=&text& id=&txtName& name=&name& required autofocus&&/td&
&td&&label for=&txtAddress&&Address&/label&&/td&
&td&&input type=&text& id=&txtAddress& name=&address&&&/td&
&td&&label for=&txtZipcode&&Zip Code&span class=&required&&*&/span&&/label&&/td&
&td&&input type=&text& id=&txtZipcode& name=&zipcode&
placeholder=&enter a 5-digit code&
required pattern=&^\d{5}$&
oninvalid=&this.setCustomValidity('Enter a 5-digit zipcode')&
oninput=&setCustomValidity('')&&&/td&
&td&Country&span class=&required&&*&/span&&/td&
&td&&select id=&selCountry& name=&country& required&
&option value=&& selected&Please select...&/option&
&option value=&AA&&AA&/option&
&option value=&BB&&BB&/option&
&option value=&CC&&CC&/option&
&/select&&/td&
&td&Gender&span class=&required&&*&/span&&/td&
&td&&label&&input type=&radio& name=&gender& value=&m& required&Male&/label&
&label&&input type=&radio& name=&gender& value=&f&&Female&/label&&/td&
&td&Preferences&span class=&required&&*&/span&&/td&
&td&&label&&input type=&checkbox& name=&color& value=&r&&Red&/label&
&label&&input type=&checkbox& name=&color& value=&g& checked&Green&/label&
&label&&input type=&checkbox& name=&color& value=&b&&Blue&/label&&/td&
&td&&label for=&txtPhone&&Phone&span class=&required&&*&/span&&/label&&/td&
&td&&input type=&tel& id=&txtPhone& name=&phone& required&&/td&
&td&&label for=&txtEmail&&Email&span class=&required&&*&/span&&/label&&/td&
&td&&input type=&email& id=&txtEmail& name=&email& required&&/td&
&td&&label for=&txtPassword&&Password&span class=&required&&*&/span&&/label&&/td&
&td&&input type=&password& id=&txtPassword& name=&password&
required pattern=&^\w{6,8}$&
placeholder=&6-8 characters&&&/td&
&td&&label for=&txtPWVerified&&Verify Password&span class=&required&&*&/span&&/label&&/td&
&td&&input type=&password& id=&txtPWVerified& name=&pwVerified& required&&/td&
&td&&label for=&dateBirthday&&Birthday&span class=&required&&*&/span&&/label&&/td&
&td&&input type=&date& id=&dateBirthday& name=&birthday& required&&/td&
&td&&label for=&timeAppt&&Appointment&span class=&required&&*&/span&&/label&&/td&
&td&&input type=&time& id=&timeAppt& name=&appointment& required&&/td&
&td&&&/td&
&td&&input type=&submit& value=&SEND& id=&btnSubmit&&&
&input type=&reset& value=&CLEAR& id=&btnReset&&&/td&
How it Works?
The attribute required specifies that input cannot be empty. The attribute autofocus sets the focus to this element.
The attribute placeholder=&text& is used to show hints on the text field as watermark. The attribute pattern=&regex& specifies an regular expression (regex) pattern to be validated for this field. The oninvalid and oninput event handlers are used to customize the error message.
Similarly, we can use required on &select& to specify input value cannot be an empty string.
For radio buttons, it is sufficient to place an required on one of the buttons. [How to specify required for checkboxes?]
HTML5 adds type=&tel& to &input&, but it is not widely supported.
HTML5 adds type=&email& to &input& for email input, which can be validated (via required).
HTML5 adds type=&date& and type=&time& to &input&. Some browsers (e.g., Chrome) could show a data-picker and time-picker.
Using JavaScript
You can use JavaScript to valid an HTML form's input field before submitting the form data to the server. The JavaScript can verify that:
An input field is required and cannot be left empty.
An input field has he required number of character (e.g., password).
A valid email address ()
A valid numeric string (e.g., phone number, zip code, credit card number), or all-letter string.
A valid date.
Screenshot
Click the image to run the demo.
HTML: &JSFormValidation.html&
&!DOCTYPE html&
&html lang=&en&&
&meta charset=&utf-8&&
&title&HTML Form Input Validation Using JavaScript&/title&
&link rel=&stylesheet& href=&JSFormValidation.css&&
&script src=&JSFormValidation.js&&&/script&
&h2&HTML Form Input Validation Using JavaScript&/h2&
&form id=&formTest& method=&get& action=&processData&&
&td&&label for=&txtName&&Name&span class=&required&&*&/span&&/label&&/td&
&td&&input type=&text& id=&txtName& name=&name&&&/td&
&td id=&elmNameError& class=&errorMsg&&&&/td&&/tr&
&td&&label for=&txtAddress&&Address&/label&&/td&
&td&&input type=&text& id=&txtAddress& name=&address&&&/td&
&td id=&elmAddressError& class=&errorMsg&&&&/td&&/tr&
&td&&label for=&txtZipcode&&Zip Code&span class=&required&&*&/span&&/label&&/td&
&td&&input type=&text& id=&txtZipcode& name=&zipcode&&&/td&
&td id=&elmZipcodeError& class=&errorMsg&&&&/td&&/tr&
&td&Country&span class=&required&&*&/span&&/td&
&td&&select id=&selCountry& name=&country&&
&option value=&& selected&Please select...&/option&
&option value=&AA&&AA&/option&
&option value=&BB&&BB&/option&
&option value=&CC&&CC&/option&
&/select&&/td&
&td id=&elmCountryError& class=&errorMsg&&&&/td&&/tr&
&td&Gender&span class=&required&&*&/span&&/td&
&td&&label&&input type=&radio& name=&gender& value=&m&&Male&/label&
&label&&input type=&radio& name=&gender& value=&f&&Female&/label&&/td&
&td id=&elmGenderError& class=&errorMsg&&&&/td&&/tr&
&td&Preferences&span class=&required&&*&/span&&/td&
&td&&label&&input type=&checkbox& name=&color& value=&r&&Red&/label&
&label&&input type=&checkbox& name=&color& value=&g&&Green&/label&
&label&&input type=&checkbox& name=&color& value=&b&&Blue&/label&&/td&
&td id=&elmColorError& class=&errorMsg&&&&/td&&/tr&
&td&&label for=&txtPhone&&Phone&span class=&required&&*&/span&&/label&&/td&
&td&&input type=&text& id=&txtPhone& name=&phone&&&/td&
&td id=&elmPhoneError& class=&errorMsg&&&&/td&&/tr&
&td&&label for=&txtEmail&&Email&span class=&required&&*&/span&&/label&&/td&
&td&&input type=&text& id=&txtEmail& name=&email&&&/td&
&td id=&elmEmailError& class=&errorMsg&&&&/td&&/tr&
&td&&label for=&txtPassword&&Password (6-8 characters)&span class=&required&&*&/span&&/label&&/td&
&td&&input type=&password& id=&txtPassword& name=&password&&&/td&
&td id=&elmPasswordError& class=&errorMsg&&&&/td&&/tr&
&td&&label for=&txtPWVerified&&Verify Password&span class=&required&&*&/span&&/label&&/td&
&td&&input type=&password& id=&txtPWVerified& name=&pwVerified&&&/td&
&td id=&elmPWVerifiedError& class=&errorMsg&&&&/td&&/tr&
&td&&&/td&
&td&&input type=&submit& value=&SEND& id=&btnSubmit&&&
&input type=&reset& value=&CLEAR& id=&btnReset&&&/td&
&td&&&/td&&/tr&
CSS: &JSFormValidation.css&
.required {
.errorMsg {
.errorBox {
border: 0;
margin: 0;
padding: 3px 10
JavaScript: &JSFormValidation.js&
window.onload =
function init() {
document.getElementById(&formTest&).onsubmit = validateF
document.getElementById(&btnReset&).onclick = clearF
document.getElementById(&txtName&).focus();
function validateForm(theForm) {
with(theForm) {
return (isNotEmpty(txtName, &Please enter your name!&, elmNameError)
&& isNumeric(txtZipcode, &Please enter a 5-digit zip code!&, elmZipcodeError)
&& isLengthMinMax(txtZipcode, 5, 5, &Please enter a 5-digit zip code!&, elmZipcodeError)
&& isSelected(selCountry, &Please make a selection!&, elmCountryError)
&& isChecked(&gender&, &Please check a gender!&, elmGenderError)
&& isChecked(&color&, &Please check a color!&, elmColorError)
&& isNumeric(txtPhone, &Please enter a valid phone number!&, elmPhoneError)
&& isValidEmail(txtEmail, &Enter a valid email!&, elmEmailError)
&& isValidPassword(txtPassword, &Password shall be 6-8 characters!&, elmPasswordError)
&& verifyPassword(txtPassword, txtPWVerified, &Different from new password!&,
elmPWVerifiedError)
function postValidate(isValid, errMsg, errElm, inputElm) {
if (!isValid) {
if (errElm !== undefined && errElm !== null
&& errMsg !== undefined && errMsg !== null) {
errElm.innerHTML = errM
if (inputElm !== undefined && inputElm !== null) {
inputElm.classList.add(&errorBox&);
inputElm.focus();
if (errElm !== undefined && errElm !== null) {
errElm.innerHTML = &&;
if (inputElm !== undefined && inputElm !== null) {
inputElm.classList.remove(&errorBox&);
function isNotEmpty(inputElm, errMsg, errElm) {
var isValid = (inputElm.value.trim() !== &&);
postValidate(isValid, errMsg, errElm, inputElm);
return isV
function isNumeric(inputElm, errMsg, errElm) {
var isValid = (inputElm.value.trim().match(/^\d+$/) !== null);
postValidate(isValid, errMsg, errElm, inputElm);
return isV
function isAlphabetic(inputElm, errMsg, errElm) {
var isValid = (inputElm.value.trim().match(/^[a-zA-Z]+$/) !== null) ;
postValidate(isValid, errMsg, errElm, inputElm);
return isV
function isAlphanumeric(inputElm, errMsg, errElm) {
var isValid = (inputElm.value.trim().match(/^[0-9a-zA-Z]+$/) !== null);
postValidate(isValid, errMsg, errElm, inputElm);
return isV
function isLengthMinMax(inputElm, minLength, maxLength, errMsg, errElm) {
var inputValue = inputElm.value.trim();
var isValid = (inputValue.length &= minLength) && (inputValue.length &= maxLength);
postValidate(isValid, errMsg, errElm, inputElm);
return isV
function isValidEmail(inputElm, errMsg, errElm) {
var isValid = (inputElm.value.trim().match(
/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/) !== null);
postValidate(isValid, errMsg, errElm, inputElm);
return isV
function isSelected(selectElm, errMsg, errElm) {
var isValid = (selectElm.value !== &&);
postValidate(isValid, errMsg, errElm, selectElm);
return isV
function isChecked(inputName, errMsg, errElm) {
var elms = document.getElementsByName(inputName);
var isChecked =
for (var i = 0; i & elms. ++i) {
if (elms[i].checked) {
isChecked =
postValidate(isChecked, errMsg, errElm, null);
return isC
function isValidPassword(inputElm, errMsg, errElm) {
var isValid = (inputElm.value.trim().match(/^\w{6,8}$/) !== null);
postValidate(isValid, errMsg, errElm, inputElm);
return isV
function verifyPassword(pwElm, pwVerifiedElm, errMsg, errElm) {
var isTheSame = (pwElm.value === pwVerifiedElm.value);
postValidate(isTheSame, errMsg, errElm, pwVerifiedElm);
return isTheS
function clearForm() {
var elms = document.querySelectorAll('.errorBox');
for (var i = 0; i & elms. i++) {
elms[i].classList.remove(&errorBox&);
elms = document.querySelectorAll('[id$=&Error&]');
for (var i = 0; i & elms. i++) {
elms[i].innerHTML = &&;
document.getElementById(&txtName&).focus();
How it Works?
We separate the HTML contents, CSS presentation styles, and JavaScript programming codes in three files.
Let's begin with the HTML:
We define an HTML form with unique id=&theForm&.
We set up a table with three columns, which displays the labels, input elements and error messages (if any), respectively. See the screenshot.
Each &input& element is assigned an unique id, so that it can be selected in JavaScript via the document.getElementById() function. It also contain a name attribute, identifying the name=value request parameter. The &td& element in the 3rd column for displaying the error message has an id ending with &Error&.
For the &select& element, we define a default no-selection &option&, with value of && (empty string) and label of &Please select...&. This is necessary so that we can detect whether the user has made a selection.
For checkboxes and radio buttons, we cannot use id, as there are more than one elements and id must be unique. Instead, we set a common name. The JavaScript would use document.getElementsByName() to select all the elements with the same name.
The CSS is simple:
A class-selector for displaying the error messages in red.
A class-selector for displaying the erroneous input element with a red border. It can be used for &input type=&text|password&& and &select&, but not for &input type=&checkbox|radio&&.
We move on to the JavaScript:
We attach the init() function as the onload event handler. That is init() runs after the page is fully loaded.
In the init() function, we attach validateForm function as the onsubmit clearForm function as the onclick and set the initial focus to the first input element having the id of txtName.
The validateForm() function calls the various input validation functions to validate the input fields. It returns true if all the input validation functions return true, resulted in the form data to be submitted to the action's url. Otherwise, it returns false, the form data will not be submitted and the current page remains.
Let's look into an input validation function isNotEmpty() in details. It takes 3 arguments, an input element, an error message, and an error message element.
It gets the value from the input element, trim() to remove the leading and trailing whitespaces. It then checks for empty string, and assigned the result to a boolean variable isValid. It invokes the postValidate() and return the boolean flag.
The postValidate() accepts 4 arguments. If the input is invalid (isValid is false), it set the innerHMTL of errElm to the errMsg, and add a class &errorBox& to inputElm. The CSS class-selector .errorBox will display the input element with a red boundary. Otherwise, it clears the innerHTML of the errElm and remove class &errorBox& from inputElm.
For input validation functions such as isNumeric(), we use regular expression (regex) to perform pattern matching, e.g., regex /^\d+$/ matches 1 regex
/^[a-zA-Z]+$/ matches /^[0-9]{5,8}$/ matches string of 5 to 8 digits. The string.match(regex) return null if no match is found. Regular expression is extremely powerful for text processing. Read && for more details.
In isValidEmail() function, we check for the email pattern of &a@b.cc& via regex /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.
In isSelected() used by &select&, the
selectedElm.value returns the value of the selected &option&.
In isChecked() used by input &type=&checkbox|radio&&, we used the document.getElementsByName() to select all elements with the common name attribute. We loop through all elements to look for .checked property.
In isValidPassword(), we use regex /^\w{6,8}$/, which accepts 6 to 8 word characters.
In clearForm(), we use document.querySelectorAll('.errorBox') to select all elements with class &errorBox&, and remove this class value from the classList. We then use document.querySelectorAll('[id$=&Error&]') to select all elements with id ending with &Error& and remove its contents (possibly previous error message).
Some notes in form input validation:
What is a valid name, address and zipcode? The name and address vary from country to country and they may contain non-ASCII characters. Zipcode may not be numeric and may contain space.
A password may contain letter, digit and special characters such as @. it probably does not contain space.
[TODO more]
Using jQuery
jQuery (a JavaScript Framework) provides elegant selectors and event handling syntax, which greatly simplifies the coding. jQuery is preferred nowadays, over raw JavaScript.
HTML &JQFormValidation.html&
Same as &JSFormValidation.html&, except the references to CSS and JavaScipt, and the inclusion of jQuery library, and may be the title.
&link rel=&stylesheet& href=&JQFormValidation.css&&
&script src=&js/jquery-1.11.2.min.js&&&/script&
&script src=&JQFormValidation.js&&&/script&
CSS &JQFormValidation.css&
Exactly the same as &JSFormValidation.css&.
JavaScript &JQFormValidation.js&
$( function() {
$('#txtName').focus();
$('#formTest').on('submit', function() {
var $form = $(this);
return isNotEmpty($form.find('#txtName'), &Please enter your name!&,
$form.find('#elmNameError'))
&& isNumeric($form.find('#txtZipcode'), &Please enter a 5-digit zip code!&,
$form.find('#elmZipcodeError'))
&& isLengthMinMax($form.find('#txtZipcode'), 5, 5, &Please enter a 5-digit zip code!&,
$form.find('#elmZipcodeError'))
&& isSelected($form.find('#selCountry'), &Please make a selection!&,
$form.find('#elmCountryError'))
&& isChecked($form.find('[name=&gender&]:checked'), &Please check a gender!&,
$form.find('#elmGenderError'))
&& isChecked($form.find('[name=&color&]:checked'), &Please check a color!&,
$form.find('#elmColorError'))
&& isNumeric($form.find('#txtPhone'), &Please enter a valid phone number!&,
$form.find('#elmPhoneError'))
&& isValidEmail($form.find('#txtEmail'), &Enter a valid email!&,
$form.find('#elmEmailError'))
&& isValidPassword($form.find('#txtPassword'), &Password shall be 6-8 characters!&,
$form.find('#elmPasswordError'))
&& verifyPassword($form.find('#txtPassword'), $form.find('#txtPWVerified'),
&Different from new password!&, $form.find('#elmPWVerifiedError'))
$('#btnReset').on('click', function() {
$('.errorBox').removeClass('errorBox');
$('td[id$=&Error&]').html('');
$('txtName').focus();
function postValidate(isValid, errMsg, errElm, inputElm) {
if (!isValid) {
if (errElm !== undefined && errElm !== null
&& errMsg !== undefined && errMsg !== null) {
errElm.html(errMsg);
if (inputElm !== undefined && inputElm !== null) {
inputElm.addClass(&errorBox&);
inputElm.focus();
if (errElm !== undefined && errElm !== null) {
errElm.html('');
if (inputElm !== undefined && inputElm !== null) {
inputElm.removeClass(&errorBox&);
function isNotEmpty(inputElm, errMsg, errElm) {
var isValid = (inputElm.val().trim() !== &&);
postValidate(isValid, errMsg, errElm, inputElm);
return isV
function isNumeric(inputElm, errMsg, errElm) {
var isValid = (inputElm.val().trim().match(/^\d+$/) !== null);
postValidate(isValid, errMsg, errElm, inputElm);
return isV
function isAlphabetic(inputElm, errMsg, errElm) {
var isValid = (inputElm.val().trim().match(/^[a-zA-Z]+$/) !== null) ;
postValidate(isValid, errMsg, errElm, inputElm);
return isV
function isAlphanumeric(inputElm, errMsg, errElm) {
var isValid = (inputElm.val().trim().match(/^[0-9a-zA-Z]+$/) !== null);
postValidate(isValid, errMsg, errElm, inputElm);
return isV
function isLengthMinMax(inputElm, minLength, maxLength, errMsg, errElm) {
var inputValue = inputElm.val().trim();
var isValid = (inputValue.length &= minLength) && (inputValue.length &= maxLength);
postValidate(isValid, errMsg, errElm, inputElm);
return isV
function isValidEmail(inputElm, errMsg, errElm) {
var isValid = (inputElm.val().trim().match(
/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/) !== null);
postValidate(isValid, errMsg, errElm, inputElm);
return isV
function isSelected(selectElm, errMsg, errElm) {
var isValid = (selectElm.val() !== &&);
postValidate(isValid, errMsg, errElm, selectElm);
return isV
function isChecked(inputElms, errMsg, errElm) {
var isChecked = inputElms.length & 0;
postValidate(isChecked, errMsg, errElm, null);
return isC
function isValidPassword(inputElm, errMsg, errElm) {
var isValid = (inputElm.val().trim().match(/^\w{6,8}$/) !== null);
postValidate(isValid, errMsg, errElm, inputElm);
return isV
function verifyPassword(pwElm, pwVerifiedElm, errMsg, errElm) {
var isTheSame = (pwElm.val() === pwVerifiedElm.val());
postValidate(isTheSame, errMsg, errElm, pwVerifiedElm);
return isTheS
How it Works
We place all the initialization operations under $( function() {...} ), which is a shorthand for $(document).ready(function() {...} ). These operations run once the ROM tree is construction, but before the external resources (such as images) are fully loaded. &ready& is a jQuery extension, which is better than onload in JavaScript.
The jQuery ID-selector $('#txtName') selects element with specific id, and set it as initial focus element.
This selects the &form& element and bind an handler to event submit. You can also use .submit(handler) as the shorthand for .on(event, handler).
$(this) holds the jQuery object under operation, i.e., the &form&. We assign it a variable $form. By convention, we prefix variable of jQuery object with '$' for ease of identification.
Find the element nested under $form, i.e., descendants of $form.
Similarly, we bind an hander to the click event for the reset button. We can use .addClass(classValue) and .removeClass(classValue) to add or remove a value from class attribute of the selected elements. We can use .html(value) to set the innerHTML of t and .val() to retrieve the value.
To check if the selector returns no matches, you can compare the .length property with zero.
Tic-Tac-Toe
Screenshot
Click the image to run the demo.
HTML &JSTicTacToe.html&
&!DOCTYPE html&
&html lang=&en&&
&meta charset=&utf-8&&
&title&Tic-Tac-Toe&/title&
&link rel=&stylesheet& href=&JSTicTacToe.css&&
&script src=&JSTicTacToe.js&&&/script&
&h1&Tic-Tac-Toe&/h1&
&td id=&cell0&&&&/td&
&td id=&cell1&&&&/td&
&td id=&cell2&&&&/td&
&td id=&cell3&&&&/td&
&td id=&cell4&&&&/td&
&td id=&cell5&&&&/td&
&td id=&cell6&&&&/td&
&td id=&cell7&&&&/td&
&td id=&cell8&&&&/td&
&/table&&br&
&input type=&button& id=&btnNewGame& value=&New Game&&
CSS &JSTicTacToe.css&
background-color:
font-family: Arial, Helvetica, sans-
font-size: 28
border-collapse:
padding: 10
border: 3px #888
text-align:
font-size: 28
width: 20%;
font-family: Consolas, monospace
#cell0 { border-style: no
#cell1 { border-style: non }
#cell2 { border-style: non }
#cell3 { border-style: so
#cell4 { border-style: sol }
#cell5 { border-style: sol }
#cell6 { border-style: so
#cell7 { border-style: sol }
#cell8 { border-style: sol }
.winningCell {
background-color: #f88;
JavaScript &JSTicTacToe.js&
window.onload =
const NUM_CELLS = 9;
const WINNING_PATTERNS
= new Array(, , , );
var crossPattern, noughtP
var crossP
function init() {
resetGame();
document.getElementById(&btnNewGame&).onclick = resetG
function resetGame() {
crossPattern = 0;
noughtPattern = 0;
crossPlaying =
for (var cellNum = 0; cellNum & NUM_CELLS; cellNum++) {
var elm = document.getElementById(&cell& + cellNum);
elm.innerHTML = &&&;
elm.className = &&;
elm.onmousedown =
function play(evt) {
if (evt) {
thisCell = evt.
thisCell = window.event.srcE
if (thisCell.innerHTML === &&&) {
if (crossPlaying) {
thisCell.innerHTML = &x&;
crossPattern |=
Math.pow(2, thisCell.id.charAt(4));
thisCell.innerHTML = &o&;
noughtPattern |=
Math.pow(2, thisCell.id.charAt(4));
if (!checkWin()) {
thisCell.onmousedown =
crossPlaying = !crossP
function checkWin() {
var theWinningPattern = -1;
var playerP
if (crossPlaying) {
playerPattern = crossP
playerPattern = noughtP
for (var i = 0; i & WINNING_PATTERNS. i++) {
if ((WINNING_PATTERNS[i] & playerPattern) === WINNING_PATTERNS[i]) {
theWinningPattern = WINNING_PATTERNS[i];
if (theWinningPattern & -1) {
for (var cellNum = 0; cellNum & NUM_CELLS; cellNum++) {
var elm = document.getElementById(&cell& + cellNum);
if (theWinningPattern & Math.pow(2, cellNum)) {
elm.className = &winningCell&;
elm.onmousedown =
How it Works?
There are three files: an HTML, a CSS and a JavaScript, which cleanly separate their respective functions. Take note that the HTML file deals only with the content and there is no script nor style embedded.
The HTML page puts up a 3x3 table of 9 cells, each with a unique id. It also include a button for creating a new game.
The CSS define the presentation style for the HTML elements. A special class-selector called &.winningCell& is defined to change the background color of the 3 winning cells.
The init() function, which is the onload handler, resets the game variables and cell contents via resetGame(), and attaches the function resetGame() as the button's onclick handler. Take note that clicking the &New Game& button does not involve refreshing of the page (which requires a costly access to the server), but simply reseting all the game variables and cell contents.
We use window.onload=init to ensure that init() is run after the page is fully loaded, so as to access the elements defined in the page.
We define a global array WINNING_PATTERNS, to keep the eight 3-in-a-row winning patterns. Each pattern is a 9-bit number, with bit-x represents cell-x. For example, the binary number
indicates that cells 0, 1, and 2 are occupied. The numbers are expressed in octal with a leading zero. (JavaScript does not seen to support binary number with a leading 0b, like C/C++/Java.) Similarly, we define two global variables, crossPattern and noughtPattern to keep track of the crosses and noughts placed on the game board so far.
A boolean flag crossPlaying is used to keep track of the current player.
The resetGame() function resets the game variables (empty the crossPattern and noughtPattern and
set the current player to &cross&). It also clears the contents of the cells, and attaches play() function as the onmousedown event handler, so that the user can click on the cell to play the game.
Whenever the user clicks on a cell, the play() event handler triggers with the mousedown event object as the argument. It first identifies the cell-clicked (with different methods for IE and non-IE browsers). It
places the current player's symbol on the game board, and updates the player's pattern. It then calls the checkWin() to check if the current player wins the game. If not, it disables this cell by removing the onmousedown handler, and toggles the current player.
The chcekWin() function checks the current player's pattern against the eight winning patterns. If the current player wins, it highlights the three winning cells by changing the cells' class attribute. The CSS class-selector will automatically display the cell with a different background color. It also disables all the cells. User has to click the &New Game& button to start a new game.
A Date Picker
Screenshot
Click the image to run the demo.
JavaScript Utilities &dateUtil.js&
function isLeapYear(year) {
return ((year % 4) === 0 && ((year % 100) !== 0 || (year % 400) === 0));
function getDaysInMonth(year, month) {
if (month === 2) {
if (isLeapYear(year)) {
return 29;
return 28;
} else if ((month === 1) || (month === 3) || (month === 5) || (month === 7)
|| (month === 8) || (month === 10) || (month === 12)) {
return 31;
return 30;
function getDayInWeek(year, month, day) {
var weekdays = [&Sunday&, &Monday&, &Tuesday&, &Wednesday&,
&Thursday&, &Friday&, &Saturday&];
var theDate = new Date(year, month-1, day);
return weekdays[theDate.getDay()];
How it Works?
The function isLeapYear(year) returns true if year is a leap year.
The function getDaysInMonth(year, month) returns the number of days in the given month (1-12) of the year (4-digit). Take note that JavaScript represents a month in the range of 0-11 (for Jan to Dec), instead of 1-12.
The function getDayInWeek(year, month, day) returns the day of the week (Sunday to Saturday). It constructs a built-in object Date with the given year, month and day, and use the getDay() function of the Date object to obtain the day of the week in the range of 0-6.
HTML &JSDatePicker.html&
&!DOCTYPE html&
&html lang=&en&&
&meta charset=&utf-8&&
&title&A Date Chooser&/title&
&script src=&JSDateUtil.js&&&/script&
&script src=&JSDatePicker.js&&&/script&
&h2&A Date Chooser&/h2&
&form id=&theForm&&
Year: &input type=&text& name=&year& id=&year& size=&4& maxLength=&4&&
Month: &select name=&month& id=&month&&
&option id=&month1& value=&1&&Jan&/option&
&option id=&month2& value=&2&&Feb&/option&
&option id=&month3& value=&3&&Mar&/option&
&option id=&month4& value=&4&&Apr&/option&
&option id=&month5& value=&5&&May&/option&
&option id=&month6& value=&6&&Jun&/option&
&option id=&month7& value=&7&&Jul&/option&
&option id=&month8& value=&8&&Aug&/option&
&option id=&month9& value=&9&&Sep&/option&
&option id=&month10& value=&10&&Oct&/option&
&option id=&month11& value=&11&&Nov&/option&
&option id=&month12& value=&12&&Dec&/option&
Day: &select name=&day& id=&day&&&/select&&
&input type=&text& name=&dayInWeek& id=&dayInWeek& readonly&&
&input type=&button& id=&btnNow& value=&Now&&
JavaScript &JSDatePicker.js&
window.onload =
var selectedY
var selectedM
var selectedD
function init() {
setToday();
updateDisplay();
document.getElementById(&year&).onchange = function() {
selectedYear=this.
updateDayDisplay();
updateDayInWeekDisplay();
document.getElementById(&month&).onchange = function() {
selectedMonth=this.
updateDayDisplay();
updateDayInWeekDisplay()
document.getElementById(&day&).onchange = function() {
selectedDay=this.
updateDayInWeekDisplay();
document.getElementById(&btnNow&).onclick = function() {
setToday();
updateDisplay();
function setToday() {
var now = new Date();
selectedYear = now.getFullYear();
selectedMonth = now.getMonth() + 1;
selectedDay = now.getDate();
function updateDisplay() {
document.getElementById(&year&).value = selectedY
updateMonthDisplay();
updateDayDisplay();
updateDayInWeekDisplay();
function updateMonthDisplay() {
document.getElementById(&month& + selectedMonth).selected =
function updateDayDisplay() {
var elm = document.getElementById(&day&);
elm.innerHTML = &&;
var daysInMonth = getDaysInMonth(selectedYear, selectedMonth);
if (selectedDay & daysInMonth) {
selectedDay = daysInM
var options = &&;
for (var day = 1; day &= daysInM day++) {
options += &&option value='& + day + &'&;
if (day === selectedDay) {
options += & selected&;
options += &&& + day + &&/option&&;
elm.innerHTML =
function updateDayInWeekDisplay() {
document.getElementById(&dayInWeek&).value
= getDayInWeek(selectedYear, selectedMonth, selectedDay);
How it Works?
The form consists of 5 input elements: a text field for the year, pull-down menus for month and day, a read-only text field for the day of the week, and a button to set the display to today. When the page is first loaded, the current date is display. If you change the year, month or day, the day of the week changes. If you change the year or month, the options in day adjust automatically, e.g., there are 28/29 days in Feb for non-leap and leap years.
Click the image to run the demo.
HTML &JSCalendarSimple.html&
&!DOCtype html&
&html lang=&en&&
&meta charset=&utf-8&&
&title&JavaScript Calendar&/title&
&link rel=&stylesheet& href=&JSCalendarSimple.css&&
&script src=&JSDateUtil.js&&&/script&
&script src=&JSCalendarSimple.js&&&/script&
&h2&Calendar&/h2&
&form id=&frmCalendar&&
&select id=&selMonth&&
&option&January&/option&
&option&February&/option&
&option&March&/option&
&option&April&/option&
&option&May&/option&
&option&June&/option&
&option&July&/option&
&option&August&/option&
&option&September&/option&
&option&October&/option&
&option&November&/option&
&option&December&/option&
&input type=&text& id=&tfYear& size=&4& maxlength=&4&&&br&&br&
&input type=&button& id=&btnPrevYear&
value=& &&
&input type=&button& id=&btnPrevMonth& value=&
&input type=&button& id=&btnToday&
value=&Today&&
&input type=&button& id=&btnNextMonth& value=&
&input type=&button& id=&btnNextYear&
&& &&&br&&br&
&table id=&tableCalendar&&&/table&
CSS &JSCalendarSimple.css&
background:
font-weight: bold
color: red
input, select {
font-family: Consolas,
font-weight:
color: blue
font-family: Consolas,
text-align:
border-collapse:
border: 1px solid black
padding: 3px 5
border: 1px solid black
JavaScript &CalendarSimple.js&
window.onload =
var thisYear, thisMonth, thisD
function init() {
setToday();
document.getElementById(&selMonth&).onchange = setM
document.getElementById(&tfYear&).onchange
document.getElementById(&btnPrevYear&).onclick
= setPreviousY
document.getElementById(&btnPrevMonth&).onclick = setPreviousM
document.getElementById(&btnNextMonth&).onclick = setNextM
document.getElementById(&btnNextYear&).onclick
= setNextY
document.getElementById(&btnToday&).onclick
document.getElementById(&frmCalendar&).onsubmit = function() {
function setToday() {
= new Date();
= now.getDate();
thisMonth = now.getMonth();
= now.getFullYear();
document.getElementById(&selMonth&).selectedIndex = thisM
document.getElementById(&tfYear&).value = thisY
printCalendar(thisYear, thisMonth);
function printCalendar(year, month) {
var daysInMonth = getDaysInMonth(year, month + 1);
var firstDayOfMonth = (new Date(year, month, 1)).getDay();
var tableInnerHTML = &&tr&&th class='sunday'&Sun&/th&&th&Mon&/th&&th&Tue&/th&&
+ &&th&Wed&/th&&th&Thu&/th&&th&Fri&/th&&th&Sat&/th&&/tr&&;
var tdCellCount = 0;
if (firstDayOfMonth !== 0) {
tableInnerHTML += &&tr&&td colspan='& + firstDayOfMonth + &'&&/td&&;
tdCellCount = firstDayOfM
for (var day = 1; day &= daysInM day++) {
if (tdCellCount % 7 === 0) {
tableInnerHTML += &&tr&&;
if ((day === thisDay) && (month === thisMonth) && (year === thisYear)) {
tableInnerHTML += &&td class='today'&& + day + &&/td&&;
} else if (tdCellCount % 7 === 0) {
tableInnerHTML += &&td class='sunday'&& + day + &&/td&&;
tableInnerHTML += &&td&& + day + &&/td&&;
tdCellCount++;
if (tdCellCount % 7 === 0) {
tableInnerHTML += &&/tr&&;
var remainingCells = 7 - tdCellCount % 7;
if (remainingCells & 7) {
tableInnerHTML += &&td colspan='& + remainingCells + &'&&/td&&/tr&&;
document.getElementById(&tableCalendar&).innerHTML = tableInnerHTML;
function setMonth() {
= document.getElementById(&tfYear&).
var month = document.getElementById(&selMonth&).selectedI
printCalendar(year, month);
function setYear() {
= document.getElementById(&tfYear&).
var month = document.getElementById(&selMonth&).selectedI
if (isValidYear(year)) {
printCalendar(year, month);
function isValidYear(year) {
if (year & 1 || year & 9999) {
alert (&Sorry, the year must be between 1 and 9999.&);
document.getElementById(&tfYear&).focus();
function setPreviousYear() {
= document.getElementById(&tfYear&).
var month = document.getElementById(&selMonth&).selectedI
if (isValidYear(year)) {
document.getElementById(&tfYear&).value =
printCalendar(year, month);
function setNextYear() {
= document.getElementById(&tfYear&).
var month = document.getElementById(&selMonth&).selectedI
if (isValidYear(year)) {
document.getElementById(&tfYear&).value =
printCalendar(year, month);
function setPreviousMonth() {
= document.getElementById(&tfYear&).
var month = document.getElementById(&selMonth&).selectedI
if (month === 0) {
month = 11;
if (isValidYear(year)) {
document.getElementById(&tfYear&).value =
document.getElementById(&selMonth&).selectedIndex =
printCalendar(year, month);
function setNextMonth() {
= document.getElementById(&tfYear&).
var month = document.getElementById(&selMonth&).selectedI
if (month === 11) {
month = 0;
if (isValidYear(year)) {
document.getElementById(&tfYear&).value =
document.getElementById(&selMonth&).selectedIndex =
printCalendar(year, month);
How it Works?
JavaScript Animation - A Digital Clock
Screenshot
Click the image to run the demo.
JavaScript &JSClockDigital.html&
&!DOCTYPE html&
&html lang=&en&&
&meta charset=&utf-8&&
&title&A JavaScript Clock&/title&
&script type=&text/javascript&&
window.onload = initC
function initClock() {
var now = new Date();
= now.getHours();
var min = now.getMinutes();
var sec = now.getSeconds();
if (min & 10) min = &0& +
if (sec & 10) sec = &0& +
document.getElementById('clockDisplay').innerHTML
= &Time is & + hr + &:& + min + &:& +
setTimeout('initClock()', 500);
&h1 id=&clockDisplay&&&/h1&
How it works?
We use the new Date() to create a Date object with the current time and assign to the variable now.
We then use the getHours(), getMinutes(), getSeconds() function of now object to retrieve the hours, minutes and seconds.
We display the clock by setting the innerHTML property of the &h1& tag. We use the getElementById() function to retrieve the &h1& tag.
The function initClock() is invoked when the browser loads this page, by attaching it to the onload event handler.
In initClock(), the setTimeout('initClock()', 500) function is used to recursively invoke the initClock() function every 500 msec, to refresh the display.
JavaScript Animation - Bouncing Balls
Screenshot
Click the image to run the demo.
HTML &JSBouncingBallSimple.html&
&!DOCTYPE html&
&html lang=&en&&
&meta charset=&utf-8&&
&title&JavaScript Bouncing balls&/title&
&link rel=&stylesheet& href=&JSBouncingBallSimple.css&&
&script src=&JSBouncingBallSimple.js&&&/script&
&h2&JavaScript Bouncing Ball&/h2&
&div id=&box&&&/div&
&img class=&ball& id=&ball& src=&images/ball_red.gif& alt=&ball&&
CSS &JSBouncingBallSimple.css&
border-color:
img.ball {
JavaScript &JSBouncingBallSimple.js&
window.onload =
const MIN_X = 20;
const MIN_Y = 80;
const WIDTH = 400;
const HEIGHT = 400;
const MAX_X = MIN_X + WIDTH - 1;
const MAX_Y = MIN_Y + HEIGHT - 1;
var ballRadius = 30;
var ballSize = ballRadius*2 + 1;
var ballCenterX = (WIDTH - 2*ballSize)*Math.random() + (MIN_X + ballSize);
var ballCenterY = (HEIGHT - 2*ballSize)*Math.random() + (MIN_Y + ballSize);
var ballSpeedX = 8;
var ballSpeedY = 6;
function init() {
var box = document.getElementById(&box&);
box.style.left = (MIN_X - 5) + &px&;
box.style.top = (MIN_Y - 5) + &px&;
box.style.width = WIDTH + &px&;
box.style.height = HEIGHT + &px&;
var balls = document.getElementsByClassName(&ball&);
balls[0].style.left = (ballCenterX - ballRadius) + &px&;
balls[0].style.top
= (ballCenterY - ballRadius) + &px&;
balls[0].style.width = ballSize + &px&;
balls[0].style.height = ballSize + &px&;
moveOneStep();
function moveOneStep() {
ballCenterX += ballSpeedX;
ballCenterY += ballSpeedY;
if (ballCenterX - ballRadius & MIN_X) {
ballSpeedX = -ballSpeedX;
ballCenterX = MIN_X + ballR
} else if (ballCenterX + ballRadius & MAX_X) {
ballSpeedX = -ballSpeedX;
ballCenterX = MAX_X - ballR
if (ballCenterY - ballRadius & MIN_Y) {
ballSpeedY = -ballSpeedY;
ballCenterY = MIN_Y + ballR
} else if (ballCenterY + ballRadius & MAX_Y) {
ballSpeedY = -ballSpeedY;
ballCenterY = MAX_Y - ballR
var balls = document.getElementsByClassName(&ball&);
balls[0].style.left = (ballCenterX - ballRadius) + &px&;
balls[0].style.top
= (ballCenterY - ballRadius) + &px&;
setTimeout(&moveOneStep()&, 60);
Ball Images
How it Works?
To perform animation in JavaScript, we use CSS's absolute positioning to position the image and then move the image. We define two CSS styles:
An id-selector box to absolutely position the container box. We use a &div id=&box&& tag for the container box by enabling its border property. In the init() function, we retrieve the &div id=&box&& element via box=document.getElementById(&box&). We then absolutely position the &div& element via box.style.left|top|width|height.
An class-selector img.ball to absolutely position the ball. We use the class-selector for the ball in order to handle more than one balls. This is because id needs to be unique, but many elements can use the same class. The ball is represented by an &img class=&ball& src=&images/ball_red.gif& /& tag. We use balls=document.getElementsByClassName(&ball&) to retrieve an array of the &img& elements. We then use balls[0].style.left|top|width|height to position the ball.
The onload event handler invokes the init(), which positions the container box, and the initial position of the ball.
The moveOneStep() function invokes setTimeout(&moveOneStep()&, 60), which recursively runs the move() at the specified time (msec) interval.
Read && on the bouncing ball algorithm. There are many limitations on doing complex animation on JavaScript. Applet is a much better platform.
Creating a one-pixel image
JavaScript's animation is often carry out by absolutely position (and re-position) an image via CSS position:absolute and imgElm.style.left|top|width|height attributes. The image's width and height is controlled via the style.width and style.height properties. An one-pixel image (which is smallest in size) can be stretched to fill the specified style.width and style.height.
To create a one-pixel image:
Launch &Paint& &rA Select the desired color &rA Fill &rA Select &Resize&, and set the width and height to 1x1 pixel &rA Save as &png& or &gif&.
The one-pixel image can be stretched to a rectangle of any size, which can be used in application such as drawing 2D bar chart. It cannot be used as a round ball though.
You can also create a one-pixel animated image, which alternates a few colors.
JavaScript Animation - Falling Snow, Falling Leave
to run the demo.
JavaScript &JSSnow.js&
window.onload =
const NUMBER = 12;
const IMAGE_PATH = &images/&
const SOURCE_IMAGES = [
&leaf_green.gif&, &leaf_orange_green.gif&, &leaf_red.gif&,
&leaf_yellow_green.gif&, &leaf_rotten.gif&];
= new Array();
= new Array();
= new Array();
= new Array();
= new Array();
var xSineMag
= new Array();
var xStepAccum = new Array();
var xMin = document.documentElement.scrollLeft + 20;
var xMax = document.documentElement.scrollLeft
+ document.documentElement.clientWidth - 20;
var yMin = document.documentElement.scrollTop + 30
var yMax = document.documentElement.scrollTop
+ document.documentElement.clientHeight - 30;
function init() {
for (var i = 0; i & NUMBER; i++) {
initItem(i);
var imgElm = document.createElement(&img&);
document.body.appendChild(imgElm);
imgElm.clasName = &images&;
imgElm.name = &images&;
imgElm.src = IMAGE_PATH + SOURCE_IMAGES[i % SOURCE_IMAGES.length];
imgElm.style.position = &absolute&;
imgElm.style.width = size[i] + &px&;
imgElm.style.height = size[i] + &px&;
moveOneStep();
function initItem(itemIndex) {
xStepAccum[itemIndex] = 0;
xSineMag[itemIndex] = 20 + Math.random() * 40;
size[itemIndex]
= 25 + Math.random() * 5;
xStep[itemIndex] = (Math.random() - 0.5) / 5;
yStep[itemIndex] = 1 + Math.random();
xPos[itemIndex] = Math.random() * (xMax - xMin - size[itemIndex]*4)
+ size[itemIndex] + xM
yPos[itemIndex] = Math.random() * (yMax - yMin - size[itemIndex]*4)
+ size[itemIndex] + yM
function moveOneStep() {
xMin = document.documentElement.scrollLeft + 20;
xMax = document.documentElement.scrollLeft
+ document.documentElement.clientWidth - 20;
yMin = document.documentElement.scrollTop + 30
yMax = document.documentElement.scrollTop
+ document.documentElement.clientHeight - 30;
var images = document.getElementsByName(&images&);
for (var i = 0; i & NUMBER; ++ i) {
yPos[i] += yStep[i];
if (yPos[i] & yMax) {
initItem(i);
yPos[i] = 0;
xStepAccum[i] += xStep[i];
var xNew = xPos[i] + Math.random()*0.3 + xSineMag[i]*Math.sin(xStepAccum[i]);
if (xNew & xMax) {
images[i].style.top
= yPos[i] + &px&;
images[i].style.left = xNew + &px&;
setTimeout(&moveOneStep()&, 100);
I collected these images from the web and converted into transparent GIF:
To use this script, place the following line in your HTML file, and also check the image file name and path in the script.
&script src=&JSSnow.js&&&/script&
How it Works
The width and height of the displayed image is controlled by the CSS style.
To convert a GIF image to transparent using PhotoShop: From &Image& menu &rA Mode
&rA Color Table &rA Select the &Dropper& &rA Click on the background. This turns the background to check-box pattern (i.e., no color) &rA Save.
To convert a JPEG image to transparent GIF using PhotoShop: From &Image& menu &rA Mode
&rA Index mode &rA Color: 256 &rA Check &Transparency&. Then, do previous step and save as GIF format.
[TODO] Convert to object-oriented.
JavaScript Animation - X-Y Plotting
Screenshot
Click the image to run the demo.
HTML &JSXYPlot.html&
&!DOCTYPE html&
&html lang=&en&&
&meta charset=&utf-8&&
&title&JavaScript XY-Plotting&/title&
&link rel=&stylesheet& href=&JSXYPlot.css&&
&script src=&JSXYPlot.js&&&/script&
&h2&JavaScript Plotting&/h2&
&fieldset&
&legend&New&/legend&
&label&X: &input type=&text& size=&3& id=&newX&&&/label&
&label&Y: &input type=&text& size=&3& id=&newY&&&/label&
&input id=&btnCreate& type=&button& value=&CREATE&&
&/fieldset&
&fieldset&
&legend&Update&/legend&
No: &select name=&updateNo& id=&updateNo& &&/select&
&label&X: &input type=&text& size=&3& id=&updateX&&&/label&
&label&Y: &input type=&text& size=&3& id=&updateY&&&/label&
&input id=&btnUpdate& type=&button& value=&UPDATE&&
&/fieldset&
&div id=&box& &&/div&
&div id=&allItems&&&/div&
CSS &JSXYPlot.css&
.item, .itemDesc {
JavaScript &JSXYPlot.js&
window.onload =
const SOURCE_IMAGE = &images/car_green.gif&;
const SIZE = 50;
const MARGIN_LEFT = 15;
const MARGIN_TOP
const X_MIN = 0;
const Y_MIN = 0;
const X_MAX = 600;
const Y_MAX = 300;
const WIDTH = X_MAX - X_MIN + 1;
const HEIGHT = Y_MAX - Y_MIN + 1;
var numItems = 0;
function init() {
var box = document.getElementById(&box&);
box.style.top = MARGIN_TOP + &px&;
box.style.left = MARGIN_LEFT + &px&;
box.style.width = WIDTH + &px&;
box.style.height = HEIGHT + &px&;
document.getElementById(&btnCreate&).onclick = newI
document.getElementById(&btnUpdate&).onclick = updateI
function newItem() {
var x = parseInt(document.getElementById(&newX&).value);
var y = parseInt(document.getElementById(&newY&).value);
var displayX = x + MARGIN_LEFT;
var displayY = y + MARGIN_TOP;
if ((x &= X_MIN) && (x &= X_MAX) && (y &= Y_MIN) && (y &= Y_MAX)) {
numItems++;
var itemImg = &&img class='item' name='item' src='&
+ SOURCE_IMAGE + &' style='width:& + SIZE
+ & height:& + SIZE + & top:& + displayY
+ & left:& + displayX + &px' /&&;
var itemDesc = &&p class='itemDesc' name='itemDesc' style='top:&
+ displayY + & left:& + displayX
+ &px'&& + numItems + &&/p&&;
document.getElementById('allItems').innerHTML += itemImg + itemD
document.getElementById('updateNo').innerHTML
+= &&option&& + numItems + &&/option&&;
function updateItem() {
var x = parseInt(document.getElementById(&updateX&).value);
var y = parseInt(document.getElementById(&updateY&).value);
var itemNo = document.getElementById(&updateNo&).value - 1;
var items = document.getElementsByName(&item&);
var itemDescs = document.getElementsByName(&itemDesc&);
if (itemNo & items.length
&& (x &= X_MIN) && (x &= X_MAX) && (y &= Y_MIN) && (y &= Y_MAX)) {
items[itemNo].style.left = x + MARGIN_LEFT + &px&;
items[itemNo].style.top
= y + MARGIN_TOP + &px&;
itemDescs[itemNo].style.left = x + MARGIN_LEFT + &px&;
itemDescs[itemNo].style.top
= y + MARGIN_TOP + &px&;
Dissecting the Program
JavaScript - Bar Chart
JavaScript Animation - Bouncing Ball on HTML 5
This example runs on browser that support HTML 5, such as Firefox and Chrome, exclude IE.
HTML 5 provides a 2D canvas, which you can draw primitive shapes such as a circle. No ball image is needed in this example.
to run the demo.
HTML &H5BouncingBall.html&
&!DOCTYPE html&
&html lang=&en&&
&meta charset=&utf-8&&
&title&Bouncing Ball (HTML 5)&/title&
var MIN_X = 0;
var MIN_Y = 0;
var WIDTH = 520;
var HEIGHT = 410;
var MAX_X = MIN_X + WIDTH - 1;
var MAX_Y = MIN_Y + HEIGHT - 1;
var ballRadius = 30;
var ballSize = ballRadius*2 + 1;
var ballCenterX = (WIDTH - 2*ballSize)*Math.random() + (MIN_X + ballSize);
var ballCenterY = (HEIGHT - 2*ballSize)*Math.random() + (MIN_Y + ballSize);
var ballSpeedX = 5;
var ballSpeedY = 3;
function init() {
var canvas = document.getElementById('box');
canvas.width = WIDTH;
canvas.height = HEIGHT;
canvas.style.border = &1px solid&;
context = canvas.getContext('2d');
setInterval(draw, 30);
function draw() {
ballCenterX += ballSpeedX;
ballCenterY += ballSpeedY;
if (ballCenterX - ballRadius & MIN_X) {
ballSpeedX = -ballSpeedX;
ballCenterX = MIN_X + ballR
} else if (ballCenterX + ballRadius & MAX_X) {
ballSpeedX = -ballSpeedX;
ballCenterX = MAX_X - ballR
if (ballCenterY - ballRadius & MIN_Y) {
ballSpeedY = -ballSpeedY;
ballCenterY = MIN_Y + ballR
} else if (ballCenterY + ballRadius & MAX_Y) {
ballSpeedY = -ballSpeedY;
ballCenterY = MAX_Y - ballR
context.clearRect(MIN_X, MIN_Y, MAX_X, MAX_Y);
context.fillStyle=&#FF0000&;
context.beginPath();
context.arc(ballCenterX, ballCenterY, ballRadius, 0, Math.PI*2, true);
context.closePath();
context.fill();
window.addEventListener(&load&, init, true);
&h2&Bouncing Ball (on HTML 5 Canvas)&/h2&
&canvas id=&box&&Canvas not supported&/canvas&
&/section&
Dissecting the Program
HTML 5 provides a new &Canvas API& to support 2D drawing. To use the canvas:
Create a canvas element via the new &canvas&&/canvas& tag.
In the script, select the canvas element (via document.getElementById()) and get the canvas' context (via canvas.getContext('2d')). Currently, only '2d' context is supported.
You can then use the context for drawing. For example, clearRect() to cle beginPath() and closePath() arc(), moveTo(), lineTo() to define a path.
We use window.addEventListener(&load&, init, true) to register an event handler (init function) to the load event.
We use setInterval(draw, 30) to schedule function draw() every 30 msec.
The ball bouncing algorithm is the same as the previous example.
JavaScript
Calculators
Screenshot
Click the image to run the demo.
HTML &JSCalculatorSimple.html&
&!DOCTYPE html&
&html lang=&en&&
&meta charset=&utf-8&&
&title&Simple JavaScript Calculator&/title&
font-family: consola,
margin-left:
margin-right:
text-align:
&h2&Simple JavaScript Calculator&/h2&
&form name=&calcForm&&
&td colspan=&4&&&input type=&text& name=&display&
style=&text-align:right&&&/td&
&td&&input type=&button& name=&btn1& value=&1&
onclick=&calcForm.display.value += '1'&&&/td&
&td&&input type=&button& name=&btn2& value=&2&
onclick=&calcForm.display.value += '2'&&&/td&
&td&&input type=&button& name=&btn3& value=&3&
onclick=&calcForm.display.value += '3'&&&/td&
&td&&input type=&button& name=&btnAdd& value=&+&
onclick=&calcForm.display.value += ' + '&&&/td&
&td&&input type=&button& name=&btn4& value=&4&
onclick=&calcForm.display.value += '4'&&&/td&
&td&&input type=&button& name=&btn5& value=&5&
onclick=&calcForm.display.value += '5'&&&/td&
&td&&input type=&button& name=&btn6& value=&6&
onclick=&calcForm.display.value += '6'&&&/td&
&td&&input type=&button& name=&btnSub& value=&-&
onclick=&calcForm.display.value += ' - '&&&/td&
&td&&input type=&button& name=&btn7& value=&7&
onclick=&calcForm.display.value += '7'&&&/td&
&td&&input type=&button& name=&btn8& value=&8&
onclick=&calcForm.display.value += '8'&&&/td&
&td&&input type=&button& name=&btn9& value=&9&
onclick=&calcForm.display.value += '9'&&&/td&
&td&&input type=&button& name=&btnMul& value=&x&
onclick=&calcForm.display.value += ' * '&&&/td&
&td&&input type=&button& name=&btnClear&
value=&C& onclick=&calcForm.display.value = ''&&&/td&
&td&&input type=&button& name=&btn0& value=&0&
onclick=&calcForm.display.value += '0'&&&/td&
&td&&input type=&button& name=&btnEqual& value=&=&
onclick=&calcForm.display.value = eval(calcForm.display.value)&&&/td&
&td&&input type=&button& name=&btnDiv& value=&/&
onclick=&calcForm.display.value += ' / '&&&/td&
How it Works?
A CSS style is defined for the &input& tag
another for the &td& tag to centralize the buttons within the cell.
A form (called &calcForm&) is defined with a text field (called &display&), and 16 buttons.
The inputs are appended to display.value. The result is evaluated via the eval() function in the onclick handler for the '=' button.
Sending an HTTP GET|POST Request via JavaScript
Sending an HTTP GET request is easier, as the parameters can be included in the hyperlink. Sending a POST request is much harder, which is typically accomplished via a HTML form with method='POST'.
Other than using a HTML form, you can also trigger a HTTP POST via JavaScript, by creating and submitting an virtual form.
&!DOCTYPE html&
&html lang=&en&&
&meta charset=&utf-8&&
&title&JavaScript Example: Sending HTTP POST Request&/title&
function sendHttpPostRequest() {
var form = document.createElement(&form&);
form.setAttribute(&method&, &post&);
form.setAttribute(&action&, &/test.php&);
var hiddenField = document.createElement(&input&);
hiddenField.setAttribute(&type&, &hidden&);
hiddenField.setAttribute(&name&, &todo&);
hiddenField.setAttribute(&value&, &update&);
form.appendChild(hiddenField);
hiddenField = document.createElement(&input&);
hiddenField.setAttribute(&type&, &hidden&);
hiddenField.setAttribute(&name&, &username&);
hiddenField.setAttribute(&value&, &peter&);
form.appendChild(hiddenField);
document.body.appendChild(form);
form.submit();
&a href=&& onclick=&sendHttpPostRequest();&&
Click to send an HTTP POST Request&/a&
Function for Sending an HTTP GET|POST Request
You can use the following JavaScript function for send an HTTP GET|POST request:
&!DOCTYPE html&
&html lang=&en&&
&meta charset=&utf-8&&
&title&JavaScript Example: Sending HTTP POST Request&/title&
function sendHttpRequest(path, params, method) {
method = method || &post&;
var form = document.createElement(&form&);
form.setAttribute(&method&, method);
form.setAttribute(&action&, path);
for (var key in params) {
if (params.hasOwnProperty(key)) {
var hiddenField = document.createElement(&input&);
hiddenField.setAttribute(&type&, &hidden&);
hiddenField.setAttribute(&name&, key);
hiddenField.setAttribute(&value&, params[key]);
form.appendChild(hiddenField);
document.body.appendChild(form);
form.submit();
&a href=&&
onclick=&sendHttpRequest('test.php', {'todo':'update', 'user':'peter'});&&
Click to send an HTTP POST Request&/a&
Duplicate Names
The previous function cannot handle duplicate names, e.g., user[]=aaa&user[]=bbb, as an object cannot have duplicate property. To support duplicate names, use two separate arrays for names and values instead, as follows:
&!DOCTYPE html&
&html lang=&en&&
&meta charset=&utf-8&&
&title&JavaScript Example: Sending HTTP POST Request&/title&
function sendHttpRequestDuplicateNames(path, nameArray, valueArray, method) {
if (nameArray.length === 0 || nameArray.length !== valueArray.length)
method = method || &post&;
var form = document.createElement(&form&);
form.setAttribute(&method&, method);
form.setAttribute(&action&, path);
for (var i = 0; i & nameArray. i++) {
var hiddenField = document.createElement(&input&);
hiddenField.setAttribute(&type&, &hidden&);
hiddenField.setAttribute(&name&, nameArray[i]);
hiddenField.setAttribute(&value&, valueArray[i]);
form.appendChild(hiddenField);
document.body.appendChild(form);
form.submit();
&a href=&&
onclick=&sendHttpRequestDuplicateNames('test.php', ['user[]', 'user[]'], ['peter', 'paul'], 'get');&&
Click to send an HTTP POST Request&/a&
AJAX POST Request
You can also use JavaScript to send an AJAX POST request. Read &AJAX Basics&.
CURD (Create-Update-Read-Delete) Database Table

我要回帖

更多关于 property read 的文章

 

随机推荐