Home
BBB Yahoo

 Home

Javascript Tips

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);
  • document.getElementById(myId").appendChild(myNewElement);
  • var myNewElement = document.CreateElement("li");var item = myElement.getElementsByTagName("li")[0];myElement.insertBefore(myNewElement, item);
  • myElement.onclick = function () {}; // Don't forget the function
  • document.attachEvent('onclick'myFunction); // For IE 8 and previous
  • document.addEventListener('click',myFunction,false); // IE 8 and previous
  • var myImage = document.getElementById("myImage);
    myImage = function {alert('You clicked my image');}
  • Your code may not work because the page isn't loaded. Here's a fix:
    function prepareEventHanders () {
        var myImage = document.getElementById("myImage");
        myImage.onclick = function () {
            alert("You clicked the image");
        }
    }
    
    windows.onload = function {
        prepareEventHandlers();
    }
    }
    
    
  • OnFocus versus OnBlur Javascript Event:

    OnFocus is when we tab or click into a field. OnBur is when we tab or click out of a field.

    var zip = document.getElementById("zipCode");
    
    zip.onfocus = function() {
        if (zip.value == "20850") {
        }
    }
    
    zip.onblur = function() {
        if (zip.value == "20850") {
        }
    }    
    }
    

Javascript == Versus ===

=== is called strict equality

x = 5; y = "5"; if (x == y) {alert('5 is the same as "5"');} //true)
if (x===y) {alert('5 is the same as "5"');} //false

You may want to use the triple equal sign all the time.


Javascript Operators

  • %—mod operator
  • a++;—increments
  • a--;—decrements
  • ||—logical OR
  • &&—logical AND
  • (condition) ? true : false;—ternary operator. Example: var doubledigit = (x > 10 ) ? true : false;

What is so great about Javascript?

  • alert

Free Javascript Tools

  • aptana
  • Firebug
  • Setting timers:
    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?
        function showHideHTML() {
        document.getElementById("myCheckbox").onclick = function() {
            if (document.getElementById("myCheckbox").checked) {
                document.getElementById("someHTML").style.display = "block";
            }
            else {
                document.getElementById("someHTML").style.display = "none";
            }
        };
    }
    
    window.onload = function() {
        showHideHTML();
    }
    



Copyright © 2011 Robert Stevens. All rights reserved.

This article was commenced on December 9, 2011. Last update: December 9, 2011.


Sponsored Ads by Google

Ad by Google

© 1996-2011 WriteExpress Corporation. All rights reserved.
WriteExpress®, Rhymer® and Unblocking Writers' Block® are registered trademarks of WriteExpress Corporation.