Tutorial:JavaScript

From Metrixstream
(Difference between revisions)
Jump to: navigation, search
(jQuery)
 
(23 intermediate revisions by one user not shown)
Line 8: Line 8:
 
   if (window["console"] && window["console"]["log"]) window["console"]["log"](str);
 
   if (window["console"] && window["console"]["log"]) window["console"]["log"](str);
 
  }
 
  }
 +
 +
</script>
 +
 +
= Scope =
 +
 +
Scope is important because variables go in and out of existence depending on where they are referenced from. This gets extremely important to understand when using variables of the same name.
 +
 +
== Example ==
 +
 +
=== Code ===
 +
 +
<script>
 +
 +
var value = 10;
 +
 +
log("A: " + value);
 +
 +
if (true) {
 +
  var value = 11;
 +
 +
  log("B: " + value);
 +
}
 +
 +
log("C: " + value);
 +
 +
</script>
 +
 +
=== Output ===
 +
 +
A: 10
 +
B: 11
 +
C: 11
 +
 +
== Example ==
 +
 +
=== Code ===
 +
 +
<script>
 +
 +
var value = 10;
 +
 +
function test() {
 +
  value = 11;
 +
 +
  log("test: " + value);
 +
}
 +
 +
log("A: " + value);
 +
 +
test();
 +
 +
log("B: " + value);
 +
 +
</script>
 +
 +
=== Output ===
 +
 +
A: 10
 +
test: 11
 +
B: 11
 +
 +
== Example ==
 +
 +
=== Code ===
 +
 +
<script>
 +
 +
var value = 10;
 +
 +
function test() {
 +
  var value = 11;
 +
 +
  log("test: " + value);
 +
}
 +
 +
log("A: " + value);
 +
 +
test();
 +
 +
log("B: " + value);
 +
 +
</script>
 +
 +
=== Output ===
 +
 +
A: 10
 +
test: 11
 +
B: 10
 +
 +
= Anonymous Functions =
 +
 +
Anonymous functions are useful because you can limit their execution to a variable... which means you can hide their execution due to scope! A good example of this is the Google Analytics javascript code. Google just wants their code to execute. They don't want anything changed.
 +
 +
== Example: Static Function ==
 +
 +
Notice how once test() is declared, it can always be called.
 +
 +
=== Code ===
 +
 +
<script>
 +
 +
function test() {
 +
  log("test");
 +
}
 +
 +
test();
 +
 +
if (true) {
 +
  test();
 +
}
 +
 +
function anotherTest() {
 +
  test();
 +
}
 +
 +
anotherTest();
 +
 +
</script>
 +
 +
=== Output ===
 +
 +
test
 +
test
 +
test
 +
 +
== Example: Anonymous Function ==
 +
 +
In this example the function only exists within the actual execution of placeholder().
 +
 +
=== Code ===
 +
 +
<script>
 +
 +
function placeholder() {
 +
  var testFunc = function() {
 +
    log("test");
 +
  };
 +
 +
  testFunc();
 +
}
 +
 +
placeholder();
 +
testFunc();
 +
 +
</script>
 +
 +
=== Output ===
 +
 +
test
 +
- Uncaught ReferenceError: testFunc is not defined
 +
 +
== Example: Anonymous Function within Anonymous Function ==
 +
 +
The above example was interesting, but seemed a little heavy because we still had to create an actual static function first. This example shows how to create an anonymous function which declares even more stuff inside it and immediately executes so nothing can get intercepted.
 +
 +
=== Code ===
 +
 +
<script>
 +
 +
(function() {
 +
  var testFunc = function() {
 +
    log("test");
 +
  };
 +
  testFunc();
 +
})();
 +
 +
testFunc();
 +
 +
</script>
 +
 +
=== Output ===
 +
 +
test
 +
- Uncaught ReferenceError: testFunc is not defined
 +
 +
= jQuery =
 +
 +
jQuery is a library that makes working with javascript much easier.
 +
 +
== Less Error-prone ==
 +
 +
=== Javascript Code ===
 +
 +
Here is an example of hiding an element using JavaScript.
 +
 +
<script>
 +
 +
var obj = document.getElementById("testId");
 +
obj.display.style = "none";
 +
 +
</script>
 +
 +
Notice any problem with that? What happens if the element testId doesn't exist? The code fails, which means the entire webpage stops functioning. jQuery is much more robust where you don't have to check if something exists... meaning simple problems like this don't sneak up when you least expect it (like friday night at midnight when your client is checking their website and no one is around to fix an easy error).
 +
 +
=== jQuery Code ===
 +
 +
<script>
 +
 +
$("#testId").hide();
 +
 +
</script>
 +
 +
== document.ready ==
 +
 +
jQuery provides a great function document.ready which lets you execute code when the page is ready to be accessed by JavaScript. document.ready is different than onload because onload gets triggered after all static resources get loaded. In the example below, document.ready will not be used just to keep the examples shorter. It is a good rule of thumb, to always wrap any immediately executing code in a document.ready block.
 +
 +
=== Code ===
 +
 +
<script>
 +
 +
$(document).ready(function() {
 +
  // add your code here
 +
});
 +
</script>
 +
== Selectors ==
 +
 +
jQuery is awesome at selecting HTML elements. The equivalent is very complex and error-prone to do in raw JavaScript. After selection, an action is normally performed, such as: hide(), show(), fadeIn(), fadeOut(), css(), addClass(), removeClass(), etc.
 +
 +
=== Hide all Divs on the webpage ===
 +
 +
<script>
 +
 +
$("div").hide();
 +
 +
</script>
 +
 +
=== Hide all elements of the class "test" on the webpage ===
 +
 +
<script>
 +
 +
$(".test").hide();
 +
 +
</script>
 +
 +
=== Hide all elements of the class "test" on the webpage ===
 +
 +
<script>
 +
 +
$(".test").hide();
 +
 +
</script>
 +
 +
=== Hide all DIV elements of the class "test" on the webpage ===
 +
 +
<script>
 +
 +
$("div.test").hide();
 +
 +
</script>
 +
 +
=== Hide an element of ID test on the webpage ===
 +
 +
<script>
 +
 +
$("#id").hide();
 +
 +
</script>
 +
 +
=== Hide an DIV element of ID test on the webpage ===
 +
 +
<script>
 +
 +
$("div#id").hide();
 +
 +
</script>
 +
 +
=== Hide all inputs that have a type property ===
 +
 +
<script>
 +
 +
$("input[type]).hide();
 +
 +
</script>
 +
 +
=== Hide all inputs that have a name property that is set to myinputname ===
 +
 +
<script>
 +
 +
$("input[name='myinputname']).hide();
 +
 +
</script>
 +
 +
=== Hide all inputs within a form of id=myform ===
 +
 +
You can refine your selection by referencing a context of another element.
 +
 +
<script>
 +
 +
$("input", "#myform").hide();
 +
 +
</script>
 +
 +
== Function Chaining ==
 +
 +
jQuery allows chaining of functions, so your code size can be extremely small.
 +
 +
This example will unhide an input element, give it a default value, add a class on it, and then focus the input.
 +
 +
$("#myinput").show().val("This is my default value").addClass("myClass").focus();
 +
 +
== Advanced Examples ==
 +
 +
=== Specify Input Text that disappears once clicked ===
 +
 +
==== HTML/CSS ====
 +
 +
<style>
 +
.preSelected {
 +
  color: #AAA;
 +
}
 +
</style>
 +
 +
<input type=text name=myname value="Please enter your name" class="preSelected">
 +
 +
==== jQuery ====
 +
 +
<script>
 +
 +
$(document).ready(function() {
 +
  $(".preSelected").click(function(evt) {
 +
    $(this).unbind("click").removeClass("preSelected").val("").focus();
 +
  });
 +
});
 
   
 
   
 
  </script>
 
  </script>

Latest revision as of 17:42, 17 August 2012

Contents

[edit] Logging

Logging is your friend. It isn't always supported, so you need to write your own wrapper around it. All logging will go to the console window which is located in the developer tools for most popular web browsers.

<script>

function log(str) {
  if (window["console"] && window["console"]["log"]) window["console"]["log"](str);
}

</script>

[edit] Scope

Scope is important because variables go in and out of existence depending on where they are referenced from. This gets extremely important to understand when using variables of the same name.

[edit] Example

[edit] Code

<script>

var value = 10;

log("A: " + value);

if (true) {
  var value = 11;

  log("B: " + value);
}

log("C: " + value);

</script>

[edit] Output

A: 10
B: 11
C: 11

[edit] Example

[edit] Code

<script>

var value = 10;

function test() {
  value = 11;

  log("test: " + value);
}

log("A: " + value);

test();

log("B: " + value);

</script>

[edit] Output

A: 10
test: 11
B: 11

[edit] Example

[edit] Code

<script>

var value = 10;

function test() {
  var value = 11;

  log("test: " + value);
}

log("A: " + value);

test();

log("B: " + value);

</script>

[edit] Output

A: 10
test: 11
B: 10

[edit] Anonymous Functions

Anonymous functions are useful because you can limit their execution to a variable... which means you can hide their execution due to scope! A good example of this is the Google Analytics javascript code. Google just wants their code to execute. They don't want anything changed.

[edit] Example: Static Function

Notice how once test() is declared, it can always be called.

[edit] Code

<script>

function test() {
  log("test");
}

test();

if (true) {
  test();
}

function anotherTest() {
  test();
}

anotherTest();

</script>

[edit] Output

test
test
test

[edit] Example: Anonymous Function

In this example the function only exists within the actual execution of placeholder().

[edit] Code

<script>

function placeholder() {
  var testFunc = function() {
    log("test");
  };

  testFunc();
}

placeholder();
testFunc();

</script>

[edit] Output

test
- Uncaught ReferenceError: testFunc is not defined

[edit] Example: Anonymous Function within Anonymous Function

The above example was interesting, but seemed a little heavy because we still had to create an actual static function first. This example shows how to create an anonymous function which declares even more stuff inside it and immediately executes so nothing can get intercepted.

[edit] Code

<script>

(function() {
  var testFunc = function() {
    log("test");
  };
  testFunc();
})();

testFunc();

</script>

[edit] Output

test
- Uncaught ReferenceError: testFunc is not defined

[edit] jQuery

jQuery is a library that makes working with javascript much easier.

[edit] Less Error-prone

[edit] Javascript Code

Here is an example of hiding an element using JavaScript.

<script>

var obj = document.getElementById("testId");
obj.display.style = "none";

</script>

Notice any problem with that? What happens if the element testId doesn't exist? The code fails, which means the entire webpage stops functioning. jQuery is much more robust where you don't have to check if something exists... meaning simple problems like this don't sneak up when you least expect it (like friday night at midnight when your client is checking their website and no one is around to fix an easy error).

[edit] jQuery Code

<script>

$("#testId").hide();

</script>

[edit] document.ready

jQuery provides a great function document.ready which lets you execute code when the page is ready to be accessed by JavaScript. document.ready is different than onload because onload gets triggered after all static resources get loaded. In the example below, document.ready will not be used just to keep the examples shorter. It is a good rule of thumb, to always wrap any immediately executing code in a document.ready block.

[edit] Code

<script>

$(document).ready(function() {
  // add your code here
});
</script>

[edit] Selectors

jQuery is awesome at selecting HTML elements. The equivalent is very complex and error-prone to do in raw JavaScript. After selection, an action is normally performed, such as: hide(), show(), fadeIn(), fadeOut(), css(), addClass(), removeClass(), etc.

[edit] Hide all Divs on the webpage

<script>

$("div").hide();

</script>

[edit] Hide all elements of the class "test" on the webpage

<script>

$(".test").hide();

</script>

[edit] Hide all elements of the class "test" on the webpage

<script>

$(".test").hide();

</script>

[edit] Hide all DIV elements of the class "test" on the webpage

<script>

$("div.test").hide();

</script>

[edit] Hide an element of ID test on the webpage

<script>

$("#id").hide();

</script>

[edit] Hide an DIV element of ID test on the webpage

<script>

$("div#id").hide();

</script>

[edit] Hide all inputs that have a type property

<script>

$("input[type]).hide();

</script>

[edit] Hide all inputs that have a name property that is set to myinputname

<script>

$("input[name='myinputname']).hide();

</script>

[edit] Hide all inputs within a form of id=myform

You can refine your selection by referencing a context of another element.

<script>

$("input", "#myform").hide();

</script>

[edit] Function Chaining

jQuery allows chaining of functions, so your code size can be extremely small.

This example will unhide an input element, give it a default value, add a class on it, and then focus the input.

$("#myinput").show().val("This is my default value").addClass("myClass").focus();

[edit] Advanced Examples

[edit] Specify Input Text that disappears once clicked

[edit] HTML/CSS

<style>
.preSelected {
  color: #AAA;
}
</style>

<input type=text name=myname value="Please enter your name" class="preSelected">

[edit] jQuery

<script>

$(document).ready(function() {
  $(".preSelected").click(function(evt) {
    $(this).unbind("click").removeClass("preSelected").val("").focus();
  });
});

</script>
Personal tools