7. history
Javascript exists since 1995
much has happened but not much has changed
it’s one of the most popular programming languages
on the web
mostly because of the advent of Ajax
8. how to implement?
<html>
<head>
<title>My first Javascript</title>
</head>
<body>
<script type=”text/javascript”>
// javascript goes here
</script>
</body>
</html>
9. comments
Comment on a single line
// this is a comment
or multiple lines
/*
multiple lines
of comments
are cool too
*/
10. variables
Variables can be strings, numbers, arrays,
objects, functions, booleans, ...
var name = "Stijn"; // string
var six = 6; // number
var colors = ["red", "blue", "green"]; // array
var wall = { type: "brick", color: "red" }; // object
var pretty = true; // boolean
11. debugging
Debugging Javascript is easiest with Firebug or
the developer toolbar in Chrome, Safari or IE
console.log("Send a general log message");
console.warn("Log a warning");
console.alert("Log an error message");
alert("You can always alert messages, but this is rather limited and irritating");
12. logic
Might look simple...
var thisIsTrue = true;
if(thisIsTrue) {
console.log("Yes, it's true!");
} else {
console.log("Don't think so...");
}
if(2 * 3 == 6) {
console.log("I can do math");
} else {
console.log("I suck at math");
}
13. logic
Might look simple... but can be tricky sometimes
var numberOne = 1;
var numberTwo = 2;
var stringOne = "1";
numberOne == numberTwo // returns false
numberOne != numberTwo // returns true
numberOne == stringOne // returns true
numberOne === stringOne // returns false
numberOne === parseInt(stringOne) // returns true
numberOne < numberTwo // returns true
numberOne > numberTwo // returns false
numberOne <= numberTwo // returns true
15. math
Might look simple... but can be tricky sometimes
var a = 10;
var b = 1;
var c = "1";
var d = a + b; // 11
var e = a + c; // "101"
b++; // 2;
16. loops
These loops all output the same
for(var i=1; i<=10; i++) {
console.log(i);
}
var i = 1;
while(i<10) {
console.log(i++);
}
var i = 1;
do {
console.log(i++);
} while(i<10);
17. l∞ps
These loops all output the same
Always make sure to
for(var i=1; i<=10; i++) {
console.log(i); validate your loops
} before running them ;)
var i = 1;
while(i<10) { You don’t want to
console.log(i++);
} make infinite loops.
var i = 1;
do {
console.log(i++);
} while(i<10);
18. arrays
Arrays have predefined functions
var colors = ["green", "red", "blue", "yellow"];
console.log(colors.length); // logs 4
console.log(colors[0]); // logs "green"
console.log(colors[3]); // logs "yellow"
colors.push("fuchsia"); // adds "fuchsia" to the end of the array
colors[2] = "sky"; // changed "blue" to "sky"
var colorsString = colors.join(",");
console.log(colorsString); // logs "green,red,sky,yellow,fuchsia";
19. objects
Objects have keys and values.
The key is a string, the value can be a number,
string, array, boolean, function or even an other
object
var me = {
name: "Stijn",
age: 28,
cool: true,
parents: ["mom", "dad"]
};
20. functions
Functions contain blocks of code that can be
executed repeatedly
function yawn() {
console.log("... yaaaawn ...");
}
yawn(); // logs "... yaaaawn ..."
21. functions
Variables can also be functions
var yawn = function() {
console.log("... yaaaawn ...");
};
yawn(); // logs "... yaaaawn ..."
22. functions
Functions can have zero or more parameters and
might return any value
var kissie = function(person1, person2) {
var theLine = person1+" and "+person2+" are sitting in a tree, k-i-s-s-i-n-g!";
return theLine;
};
console.log(kissie("Will", "Kate"));
23. scope
Variables might be “global” or “local” depending
on the location where you declare them.
When a variable is declared within a function
using the var keyword, it will only be available
within this function. Code outside that function
wouldn’t be able to access it.
24. scope
Variables that are declared within a function
aren’t accessible outside the function.
function whatsMyName() {
var name = "Stijn";
console.log(name);
}
whatsMyName(); // logs "Stijn"
console.log(name); // logs undefined
25. scope
But variables that are declared outside a function
can be accessed within a function.
var name;
function whatsMyName() {
name = "Stijn";
console.log(name);
}
whatsMyName(); // logs "Stijn"
console.log(name); // logs "Stijn"
26. scope
Remember: Variables are declared with the var
keyword. Declare a variable within a function and
it’s only accessible within the function.
var name = "Stijn";
function whatsMyName() {
var name = "Ben";
console.log(name);
}
whatsMyName(); // logs "Ben"
console.log(name); // logs "Stijn"
34. DOM
An XML structure based on the HTML
“How the browser sees and works with HTML”
<html>
<head>
<title>This is an awesome HTML page.</title>
</head>
<body>
<h1>Awesome!</h1>
<p>Totally rad, dude.</p>
</body>
</html>
36. why jQuery?
easy to use Javascript
a lot of usefull predefined functions and methods
“write less, do more”
do it all (some other libraries are specialized in x or y)
lightweight
wide range of plugins available for various specific
needs
easy to learn
37. what is jQuery?
it’s a javascript library that simplifies the use of
javascript
especially for HTML document traversing, event
handling, animating, Ajax interactions, ...
it’s just plain old javascript and open-source:
http://code.jquery.com/jquery-latest.js
38. how to implement?
<html>
<head>
<title>My first jQuery</title>
</head>
<body>
<script type=”text/javascript” src="jquery.js"></script>
<script type=”text/javascript”>
// javascript goes here
</script>
</body>
</html>
59. All selector $(“*”)
Get all elements from the DOM
Is extremely slow and not recommended
var numberOfElements = $("*").length;
console.log("jQuery found "+numberOfElements+" elements on this page");
60. Element selector $(“tagname”)
Select all elements with a specific tagName
No special characters needed
$("div").css("border", "1px solid red");
61. ID selector $(“#id”)
Selects a single element with the given ID attribute
Very efficient, one of the quickest ways to get an
element
The ID selector uses a hash before it’s name
$("#myDiv").css("border", "1px solid red");
Notice: Each ID value must be used only once within a document, otherwise this
document won’t be valid. If more than one element has been assigned the same
ID, jQuery will only select the first. This behavior should not be relied on though.
62. Class selector $(“.classname”)
Select all elements with the given class
An element can have multiple classes, only one of them
must match
The class selector uses a dot before the class name
$(".myClass").css("border", "1px solid red");
63. Multiple selector $(“a, b, c, ...”)
jQuery allows multiple selections methods in one
selector string
It will select the combined result of all the specified
selectors
Combine as many selectors as you like by the use of
commas
$("h1, #myDiv, .myClass").css("border", "1px solid red");
64. Attribute selector $(“[attribute]”)
Select elements by their attribute
var numberOfElements = $("[id]").length;
console.log("I found "+numberOfElements+" on this page with an ID attribute");
$("div[id]").css("border", "1px solid red");
$("input[value='Stijn']").css("border", "1px solid red");
65. Attribute selector $(“[attribute]”)
Advanced attribute selectors
$('input[name="abc"]') // where name equals abc
$('input[name!="abc"]') // where name is not abc
$('input[name^="abc"]') // where name starts with abc
$('input[name$="abc"]') // where name ends with abc
$('input[name*="abc"]') // where name contains the characters abc
$('input[name~="abc"]') // where name contains the word abc
66. Descendants $(“ancestor descendant”)
Select all elements that are descendants of a given
ancestor
$("form input").css("border", "1px solid red");
67. Children $(“parent > child”)
Select all elements that are descendants of a given
ancestor, but only if they are a direct child element of
the ancestor
$("ul.topnav > li").css("border", "1px solid red");
68. Double column $(“:abc”)
There are a bunch of predefined selectors
$("li:odd") // select all odd li elements
$("li:even") // select all even li elements
$("li:first") // select the first li element
$("li:last") // select the last li element
$("li:eq(4)") // select the 5th li element
$(":input") // select all input fields
$(":button") // select all buttons
$(":checkbox") // select all checkboxes
$(":radio") // select all radio elements
$(":checked") // select all checked checkboxes and radio buttons
$(":selected") // select all selected option elements
70. .html()
Without a parameter it will return the html content of
the first element in the selector
If you provide a html or text string in the first parameter,
the html content of all elements in the selector will be
updated
console.log($('body').html());
$('body').html("<h1>My pagetitle</h1>");
71. .text()
Without a parameter it will return the text content of the
first element in the selector
If you provide a text string in the first parameter, the
text content of all elements in the selector will be
updated
console.log($('body').text());
$('body').text("<h1>HTML won’t work</h1>");
72. .empty()
Remove all text and DOM elements within the selector
$('#myDiv').empty();
73. .val()
Get the current value of the first element from the
selector
The .val() method is primarily used to get the values
from form elements
$("input:checkbox:checked").val();
75. .attr(attribute, value)
Without setting the value parameter, jQuery returns the
value of the attribute of the first element in the selector
$("img").attr("src");
If you provide a second parameter (value), you set the
attribute of all selected elements to this new value
$("img").attr("src", "myImage.jpg");
76. .css(name, value)
Without setting the value parameter, jQuery returns the
specific css value of the first element in the selector
$("a").css("color"); // red
If you provide a second parameter (value), you set the
css value to this new value
$("a").css("color", "#FF3300");
77. .css(map)
The css function allows an object parameter too
$("a").css({
"color": "#FF3300",
"text-decoration": "none"
});
78. class functions
some useful class functions
$("a").addClass("active"); // adds the class "active"
$("a").removeClass("active"); // removes the class "active"
$("a").hasClass("active"); // returns true or false
$("a").toggleClass("active", "inactive"); // toggle the class
80. .eq(index)
Returns the element at the specified index number in
the selection
First item is zero (zero-based index)
$("li").eq(4);
81. .eq(-index)
Returns the element at the specified index number in
the selection counting from the back
$("li").eq(-1);
82. lookup functions
.first() // select the first item from the selected elements
.last() // select the last item from the selected elements
.next() // select the next item in the DOM
.nextAll() // select all the next items in the DOM
.prev() // select the previous item in the DOM
.prevAll() // select all the previous items in the DOM
84. chaining
jQuery is powerful because it’s built on the concept of
chaining
$(selector).function().function().function()
$("li").css("border", "1px solid red").first().addClass("first").children("div").hide();
86. $(document).ready(callback);
the first event that everyone knows
This callback event is triggered when the DOM is fully
loaded
$(document).ready(function() {
alert("Welcome on this page!");
});
Notice: the document selector doesn’t need quotes because “document” is a
native javascript object. Try console.log(document); to see the full object.
87. .click(callback)
Bind a mouse click event to the selected elements
$("#myButton").click(function() {
alert("Thank you for clicking my button");
});
88. “this”
Within a callback function you can always use the “this”
keyword to select the current element
$("#myButton").click(function() {
$(this).toggleClass("clicked");
});
89. .dblClick()
Bind a double mouse click event to the selected
elements
$("#myButton").dblClick(function() {
alert("Thank you for double clicking my button");
});
90. hover functions
many different options of doing hovers
var over = function() {
console.log("hovered over the div");
};
var out = function() {
console.log("daddy left the div");
};
$("div").mouseover(over);
$("div").mouseout(out);
$("div").hover(over, out);
92. .fadeIn(speed, callback)
Display or hide the selected elements by fading them in
or out
$("#myDiv").fadeIn(500);
$("#anotherDiv").fadeOut(500, function() {
// this function will be called after the fadeout
});
93. .slideDown(speed, callback)
Display or hide the selected elements by sliding them
up or down
$("#slider").slideDown(1000, function() {
$(this).slideUp(1000);
});
94. .delay(duration)
Set a timer to delay the execution of subsequent items
in the queue.
$("#myDiv").slideDown(500).delay(300).fadeOut(500);
95. .animate(map, duration)
Animate CSS differences by mapping an object in the
first parameter of the animate function.
var cssProperties = {
"border": "10px solid red",
"background-color": "black",
"font-size": "100px"
};
$("#myDiv").animate(cssProperties, 500);
97. Ajax
Make file requests without refreshing the page
Just like a call to an image but possibility to send and
get data (xml, json, html, text, script, ...)
Callbacks don’t run instantly, the callback is triggered
when the requested URL chooses to respond, in other
words: you have to wait for the callback to continue
(asynchronous)
98. $.get(url, callback);
If you want to get some data asynchronously
The callback function gets a parameter with the
responded data
$.get("randomHtmlSnippet.txt", function(dataResponse) {
$("#result").html(dataResponse);
});
99. ...loading...
It’s always a good idea to warn the user that your Ajax
call is running and he should wait for a moment
$("#myButton").click(function() {
$("#loader").show();
$.get("someRandomHtmlSnippet.txt", function(dataResponse) {
$("#result").html(dataResponse);
$("#loader").hide();
});
});
100. $.post(url, data, callback);
Good if you want to send and receive data
asynchronously
The callback function gets a parameter with the
responded data
var data = {
"email": "stijn@thesedays.com",
"name": "Stijn Van Minnebruggen"
};
$.post("sendEmail.php", data, function(dataResponse) {
alert(dataResponse);
});
102. .each(function(index){ ... })
The each function allows easy DOM looping
Use the this keyword to call each element in the
callback
the callback gets an index parameter
$("li").each(function(index) {
$(this).html("This is list item number "+index);
});
103. $.browser
Object that contains flags for the useragent
if($.browser.msie) {
alert("Really? :P");
}
104. $.support
Rather than using $.browser it’s recommended to
check for a specific support
$("p").html("This frame uses the W3C box model:
<span>"+jQuery.support.boxModel+"</span>"); // true