SlideShare a Scribd company logo
1 of 107
Download to read offline
jQuery
introduction
Stijn Van Minnebruggen
web developer at




twitter.com/donotfold
www.donotfold.be
jQuery
introduction
course overview
introduction to Javascript
DOM
jQuery
  why jQuery?
  what is jQuery?
  how to implement?
course overview
methods
events
effects
Ajax
utilities
Javascript
a brief introduction
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
how to implement?
<html>
<head>

   <title>My first Javascript</title>

</head>
<body>

   <script type=”text/javascript”>

   // javascript goes here

   </script>

</body>
</html>
comments
Comment on a single line

// this is a comment


or multiple lines

/*

multiple lines
of comments
are cool too

*/
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
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");
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");
}
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
math
Might look simple...

var a = 10;
var b = 1;
var c = "1";

var d = a + b;
var e = a + c;

b++;
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;
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);
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);
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";
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"]

};
functions
Functions contain blocks of code that can be
executed repeatedly

function yawn() {
   console.log("... yaaaawn ...");
}

yawn(); // logs "... yaaaawn ..."
functions
Variables can also be functions

var yawn = function() {
   console.log("... yaaaawn ...");
};

yawn(); // logs "... yaaaawn ..."
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"));
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.
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
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"
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"
DOM
document object model
HTML vs DOM
Before you want to implement Javascript on your website
it is key to know that Javascript works on the DOM, not
on the HTML.
HTML vs DOM
HTML vs DOM


HTML
 (text)
HTML vs DOM


HTML      Browser
 (text)
HTML vs DOM


HTML      Browser   DOM
 (text)             (XML)
HTML
Just plain text.


<html>
<head><title>This is an awesome HTML page.</title></head>
<body>
<h1>Awesome!</h1>
<p>Totally rad, dude.</p>
</body>
</html>
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>
jQuery
javascript library
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
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
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>
jQuery
basics
jQuery introduction
$
$ = jQuery
$ = jQuery
you can either choose to use $ or jQuery
 in your code, these variables are equal
$(selector)
get a DOM
      element


$(selector)
$(selector).function();
$(selector).function();
                execute a
                  jQuery
                 function
$(selector).function(parameters);
optional
                     parameters


$(selector).function(parameters);
optional
     get a DOM           parameters
      element


$(selector).function(parameters);
                 execute a
                   jQuery
                  function
rule of thumb:


$(selector).function(parameters);
example:


$(“h2”)
example:


  $(“h2”)
 get all H2
 elements
from DOM
example:


$(“h2”).css();
example:


$(“h2”).css();
         execute the
        jQuery “css”
           function
example:


$(“h2”).css(“color”, “#FFCC33”);
example:


$(“h2”).css(“color”, “#FFCC33”);

            set the color
            to #FFCC33
jQuery
selectors
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");
Element selector $(“tagname”)
   Select all elements with a specific tagName
   No special characters needed


$("div").css("border", "1px solid red");
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.
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");
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");
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");
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
Descendants $(“ancestor descendant”)
   Select all elements that are descendants of a given
   ancestor


$("form input").css("border", "1px solid red");
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");
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
functions
basic manipulation
.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>");
.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>");
.empty()
  Remove all text and DOM elements within the selector


$('#myDiv').empty();
.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();
functions
attributes and classes
.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");
.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");
.css(map)
   The css function allows an object parameter too


$("a").css({
    "color": "#FF3300",
    "text-decoration": "none"
});
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
functions
lookups
.eq(index)
   Returns the element at the specified index number in
   the selection
   First item is zero (zero-based index)


$("li").eq(4);
.eq(-index)
   Returns the element at the specified index number in
   the selection counting from the back


$("li").eq(-1);
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
chaining
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();
functions
events
$(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.
.click(callback)
      Bind a mouse click event to the selected elements


$("#myButton").click(function() {

      alert("Thank you for clicking my button");

});
“this”
      Within a callback function you can always use the “this”
      keyword to select the current element


$("#myButton").click(function() {

      $(this).toggleClass("clicked");

});
.dblClick()
      Bind a double mouse click event to the selected
      elements


$("#myButton").dblClick(function() {

      alert("Thank you for double clicking my button");

});
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);
functions
effects
.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
});
.slideDown(speed, callback)
  Display or hide the selected elements by sliding them
  up or down


$("#slider").slideDown(1000, function() {
    $(this).slideUp(1000);
});
.delay(duration)
  Set a timer to delay the execution of subsequent items
  in the queue.


$("#myDiv").slideDown(500).delay(300).fadeOut(500);
.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);
functions
Ajax
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)
$.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);

});
...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();

      });

});
$.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);
});
jQuery
utilities
.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);

});
$.browser
   Object that contains flags for the useragent


if($.browser.msie) {
    alert("Really? :P");
}
$.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
need help?
bookmark the docs
docs.jquery.com
thanks!
Stijn Van Minnebruggen
twitter.com/donotfold
www.donotfold.be




http://labs.thesedays.com
http://www.thesedays.com

More Related Content

What's hot

Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologyDaniel Knell
 
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2KZepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2KThomas Fuchs
 
Working With JQuery Part1
Working With JQuery Part1Working With JQuery Part1
Working With JQuery Part1saydin_soft
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuerymanugoel2003
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with DjangoSimon Willison
 
Write Less Do More
Write Less Do MoreWrite Less Do More
Write Less Do MoreRemy Sharp
 
Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016Colin O'Dell
 
Swift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CSwift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CAlexis Gallagher
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQueryZeeshan Khan
 
05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboardsDenis Ristic
 

What's hot (20)

Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2KZepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2K
 
Jquery
JqueryJquery
Jquery
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 
jQuery
jQueryjQuery
jQuery
 
JQuery introduction
JQuery introductionJQuery introduction
JQuery introduction
 
JavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talkJavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talk
 
Working With JQuery Part1
Working With JQuery Part1Working With JQuery Part1
Working With JQuery Part1
 
jQuery
jQueryjQuery
jQuery
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with Django
 
J query training
J query trainingJ query training
J query training
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
Write Less Do More
Write Less Do MoreWrite Less Do More
Write Less Do More
 
Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016
 
jQuery in 15 minutes
jQuery in 15 minutesjQuery in 15 minutes
jQuery in 15 minutes
 
jQuery
jQueryjQuery
jQuery
 
Swift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CSwift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-C
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards
 

Viewers also liked

Viewers also liked (6)

So
SoSo
So
 
Canvas
CanvasCanvas
Canvas
 
jQuery basics
jQuery basicsjQuery basics
jQuery basics
 
Choosing Lenses For Power Led Based Luminaire
Choosing Lenses For Power Led Based LuminaireChoosing Lenses For Power Led Based Luminaire
Choosing Lenses For Power Led Based Luminaire
 
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job? Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
 
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldaba
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika AldabaLightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldaba
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldaba
 

Similar to jQuery introduction

jQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and PerformancejQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and PerformanceJonas De Smet
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsJarod Ferguson
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to JavascriptAnjan Banda
 
Week 4 - jQuery + Ajax
Week 4 - jQuery + AjaxWeek 4 - jQuery + Ajax
Week 4 - jQuery + Ajaxbaygross
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
JavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingJavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingRadoslav Georgiev
 
JavaScript Misunderstood
JavaScript MisunderstoodJavaScript Misunderstood
JavaScript MisunderstoodBhavya Siddappa
 
Jquery tutorial-beginners
Jquery tutorial-beginnersJquery tutorial-beginners
Jquery tutorial-beginnersIsfand yar Khan
 
jQuery - Tips And Tricks
jQuery - Tips And TricksjQuery - Tips And Tricks
jQuery - Tips And TricksLester Lievens
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypesVarun C M
 
Jquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript BasicsJquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript BasicsEPAM Systems
 
Lecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdfLecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdfLê Thưởng
 
Intro to jQuery
Intro to jQueryIntro to jQuery
Intro to jQueryAlan Hecht
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Tsuyoshi Yamamoto
 
the next web now
the next web nowthe next web now
the next web nowzulin Gu
 

Similar to jQuery introduction (20)

jQuery
jQueryjQuery
jQuery
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues
 
jQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and PerformancejQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and Performance
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
Week 4 - jQuery + Ajax
Week 4 - jQuery + AjaxWeek 4 - jQuery + Ajax
Week 4 - jQuery + Ajax
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
JavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingJavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft Training
 
J query
J queryJ query
J query
 
JavaScript Misunderstood
JavaScript MisunderstoodJavaScript Misunderstood
JavaScript Misunderstood
 
Jquery tutorial-beginners
Jquery tutorial-beginnersJquery tutorial-beginners
Jquery tutorial-beginners
 
jQuery - Tips And Tricks
jQuery - Tips And TricksjQuery - Tips And Tricks
jQuery - Tips And Tricks
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
Jquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript BasicsJquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript Basics
 
Lecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdfLecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdf
 
Java script
Java scriptJava script
Java script
 
Intro to jQuery
Intro to jQueryIntro to jQuery
Intro to jQuery
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
 
the next web now
the next web nowthe next web now
the next web now
 

Recently uploaded

IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfDaniel Santiago Silva Capera
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Babel Compiler - Transforming JavaScript for All Browsers.pptx
Babel Compiler - Transforming JavaScript for All Browsers.pptxBabel Compiler - Transforming JavaScript for All Browsers.pptx
Babel Compiler - Transforming JavaScript for All Browsers.pptxYounusS2
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPathCommunity
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxMatsuo Lab
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...DianaGray10
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IES VE
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1DianaGray10
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
Cloud Revolution: Exploring the New Wave of Serverless Spatial Data
Cloud Revolution: Exploring the New Wave of Serverless Spatial DataCloud Revolution: Exploring the New Wave of Serverless Spatial Data
Cloud Revolution: Exploring the New Wave of Serverless Spatial DataSafe Software
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAshyamraj55
 
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdfJamie (Taka) Wang
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationIES VE
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfinfogdgmi
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1DianaGray10
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Commit University
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopBachir Benyammi
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Adtran
 
Introduction to Quantum Computing
Introduction to Quantum ComputingIntroduction to Quantum Computing
Introduction to Quantum ComputingGDSC PJATK
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaborationbruanjhuli
 

Recently uploaded (20)

IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Babel Compiler - Transforming JavaScript for All Browsers.pptx
Babel Compiler - Transforming JavaScript for All Browsers.pptxBabel Compiler - Transforming JavaScript for All Browsers.pptx
Babel Compiler - Transforming JavaScript for All Browsers.pptx
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation Developers
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptx
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
Cloud Revolution: Exploring the New Wave of Serverless Spatial Data
Cloud Revolution: Exploring the New Wave of Serverless Spatial DataCloud Revolution: Exploring the New Wave of Serverless Spatial Data
Cloud Revolution: Exploring the New Wave of Serverless Spatial Data
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
 
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdf
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 Workshop
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™
 
Introduction to Quantum Computing
Introduction to Quantum ComputingIntroduction to Quantum Computing
Introduction to Quantum Computing
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
 

jQuery introduction

  • 2. Stijn Van Minnebruggen web developer at twitter.com/donotfold www.donotfold.be
  • 4. course overview introduction to Javascript DOM jQuery why jQuery? what is jQuery? how to implement?
  • 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
  • 14. math Might look simple... var a = 10; var b = 1; var c = "1"; var d = a + b; var e = a + c; b++;
  • 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"
  • 28. HTML vs DOM Before you want to implement Javascript on your website it is key to know that Javascript works on the DOM, not on the HTML.
  • 31. HTML vs DOM HTML Browser (text)
  • 32. HTML vs DOM HTML Browser DOM (text) (XML)
  • 33. HTML Just plain text. <html> <head><title>This is an awesome HTML page.</title></head> <body> <h1>Awesome!</h1> <p>Totally rad, dude.</p> </body> </html>
  • 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>
  • 41. $
  • 43. $ = jQuery you can either choose to use $ or jQuery in your code, these variables are equal
  • 45. get a DOM element $(selector)
  • 47. $(selector).function(); execute a jQuery function
  • 49. optional parameters $(selector).function(parameters);
  • 50. optional get a DOM parameters element $(selector).function(parameters); execute a jQuery function
  • 53. example: $(“h2”) get all H2 elements from DOM
  • 55. example: $(“h2”).css(); execute the jQuery “css” function
  • 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

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n
  67. \n
  68. \n
  69. \n
  70. \n
  71. \n
  72. \n
  73. \n
  74. \n
  75. \n
  76. \n
  77. \n
  78. \n
  79. \n
  80. \n
  81. \n
  82. \n
  83. \n
  84. \n
  85. \n
  86. \n
  87. \n
  88. \n
  89. \n
  90. \n
  91. \n
  92. \n
  93. \n
  94. \n
  95. \n
  96. \n
  97. \n
  98. \n
  99. \n
  100. \n
  101. \n
  102. \n
  103. \n
  104. \n
  105. \n
  106. \n
  107. \n
  108. \n
  109. \n
  110. \n
  111. \n
  112. \n
  113. \n
  114. \n