By Robert John Stevens, CEO of WriteExpress Corporation
Javascript Tips
Javascript is a C-based, case-sensitive, interpretive language. Each statement should end with a semi-colon.
You can put the script statement anywhere but if the same code is used across pages, put it in its own file and link to it:
HTML5:
HTML4:
Put the script statement at the bottom of the page just before the <\/body> tag so the page loads faster, unless the Javascript is used to generate the page itself.
The keyword var is not required to define a variable but it is recommended to avoid unexpected results.
Surround strings with either double quotes or single quotes but not both
Boolean values true or false are lowercase.
Javascript Samples
Anything written with hyphens in CSS become camelCase (no spaces, initial lower case and then subsequent words begin with an upper case letter).
Semi-colons are used only to end statements, and are not used inside of quotes.
myElement.style.color="red";
myElement.style.color="#FFF";
myElement.style.left = "10px";
myElement.style.backgroundRepeat = "repeat-x";
myElement.style.width="600px";
myElement.style.fontWeight="bold";
myElement.style.backgroundColor="#FF0000";
myElement.style.className = "myClassName";
myElement.style.className = ""; // Clears the class name
myElement.getAttribute("align");
myElement.setAttribute("align","left");
console.log(mainElement.innerHTML);
var myNewElement = document.CreateElement("li");myElement.append(myNewElement);
var li = document.createElement('li');li.innerHTML = "text";ul.appendChild(li);
function hello() {
alert("Hello");
}
setTimeout (hello, 4000);
How to use a timer to rotate images using Javascript
var myImage = document.getElementById("someImageId");
var imageArray = ["g/one.gif","g/two.gif","g/three.gif"]
var i = 0;
function changeImage() {
myImage.setAttribute("src",imageArray[i]);
i++
if (i >= imageArray.length) {
i = 0;
}
}
var intervalHandle = setInterval(changeImage, 4000);
myImage.onclick = function () {
clearInterval(intervalHandle);
}
document.forms.myName (where myName is the name of the form)
document.forms.myName.name (where name is a name of a field on the form)
How to handle a submit event on a form
function prepareEventHandlers() {
document.getElementById("myFormId").onsubmit = function() {
//Prevent the form from submitting if no zip code
if (document.getElementById("zip").value == "") {
document.getElementById("errorMsg").innerHTML = "Please enter a zip code";
// stop the form from submitting
return false;
}
else {
document.getElementById("errorMsg").innerHTML = "";
return true;
}
};
}
window.onload = function() {
prepareEventHandlers();
}
How do I show and hide HTML via a checkbox being checked or unchecked?