jQuery

What is JQuery?

  • Fast, small (32kB), open-source
  • Feature-rich
  • Cross Browser
  • Ajax
  • Event Handling
  • HTML document traversal and manipulation
  • Animation

Basic knowledge of...

  • HTML
  • CSS
  • Javascript

using jQuery

  • Local Hosted
  • Content Delivery Network (CDN)

CDN - Hosted Content

Content Delivery Network

A large distributed system of proxy servers deployed in multiple data centers via the Internet.

Content may exist on several servers. When a user makes a request to a CDN hostname, DNS will resolve to an optimized server (based on location, availability, cost, and other metrics) and that server will handle the request.

Advantages to using a CDN

  • Speed: end-users loads your content quicker
  • Performance: Your server can do important stuff
  • Security: can off-set DDoS attacks

CDN Servies

  • Amazon CloudFront
  • Microsoft Azure
  • Rackspace
  • and much more...

Adding jQuery to your project

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Intro to jQuery</title>
  <!-- here? -->
</head>
<body>
  

  <!-- here? -->
</body>
</html>

Keep it simple for now...

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Intro to jQuery</title>
</head>
<body>
  

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
  <script src="/js/main.js"></script>
</body>
</html>
$(document).ready(function(){

  // code here

});
$(document).load(function(){

  // code here

});

$(document).ready();

$(document).load();

Ready vs Load

How is 'ready' event different from 'load'?

Ready - executes when HTML-Document is loaded and DOM is ready. Images and/or Media files have not complete downloading

 Load - executes when complete page is fully loaded, including all frames, objects, images, and media.

document.ready shortcut

$(function(){
    // code runs when DOM is ready!
});

Selecting an Element

$( '#mainLogo' );

$( '.navItems' );

$( '.newsPost p:first-child' );

$( 'form.logIn input:checkbox' );

$( '.container > header' );

$( '.newPost + .newsPost' );

$ is the variable where jQuery assigns itself by default


 jQuery takes a css selector as an argument to select ONE or MORE elements.

 

Depending on what you're looking for the return value may change.

"Inspect what you expect"

What do you get?

You're given a jQuery DOM Object. It's not your usual HTMLEntity DOM Object.

It's been sprinkled, it's been... jQueryfied.io™

Now you can start using jQuery methods.

$( '#mainLogo' ).html();

$( '.navItems' ).hide();

$( '.newsPost p:first-child' ).fadeIn('slow');

$( 'form.logIn input:checkbox' ).click(console.log);

$( '.container > header' ).css('background-color', '#333');

$( '.newPost + .newsPost' ).css('border-right', '2px solid #333');

$( 'form.logIn input' ).val();

Haz Element? Good.

$( '#mainLogo' ).html();

$( '.navItems' ).addClass('active');

$( '.newsPost p:first-child' ).css('background-color', '#333666');

$( 'form.logIn input:checkbox' ).click(showSurprise);

$( '.container > header' ).hide();

$( '.newPost + .newsPost' ).remove();

Now you that you have retrieved your element from jQuery there are a number of methods available to you.

Getter and Setter

<!-- worldnews.com/ -->
<div id="topNewsPost">
    <header>Marty McFly goes back in time and kills Donald Trump.</header>
    <p>The World rejoices!</p>
</div>

jQuery likes the getter and setter pattern. This means  that if you can use a method to get a value, you can also SET that value by giving it your value.

// main.js
$('#topNewsPost header').text(); // what is returned?

$('#topNewsPost header').text('JSON SEWELL CREATES PIDGIN SCRIPT'); // sets!
<!-- worldnews.com/ -->
<div id="topNewsPost">
    <header>JSON SEWELL CREATE PIDGIN SCRIPT</header>
    <p>The World rejoices!</p>
</div>

Chaining

<div id="topNewsPost">
    <header>JSON SEWELL CREATE PIDGIN SCRIPT</header>
    <p>The World rejoices!</p>
</div>

Having a jQuery element you can chain methods to continue working on that same element*.

$('#topNewsPost header')
    .text('JSON SEWELL CREATES PIDGIN SCRIPT')
    .css('font-size', '60px')
    .fadeOut()
;

You can continue to chain methods unless you use a method which will return a DOM element e.g. .parent(), .siblings(), or any traversal method.

Events

$( '.topNewsPost' ).click(function(event){
    this.html('<p>HACKED</p>');
});

$( '.topNewsPost' ).dblclick(function(event){
    this.html('<p>DOUBLE HACKED</p>');
});

$( '.topNewsPost' ).mouseover(function(event){
    // maybe something even more custom?
});

some syntactic sugar for your events

// equivalent to first example from above
var topNewPostEl = document.querySelectorAll('.topNewPost');

topNewPostEl.addEventlistener('click', function(event) {
    this.innerHTML = 'HACKED';
});

Events

As with vanilla Javascript, jQuery accepts a function as an argument commonly referred to as the Event Listener.

 

The Event Listener should have define a parameter which will be the Event object.
 

this

$( '.topNewsPost' ).click(function(event){
    console.log(this);            // what is shown in the console?
    console.log(this.html);       // `.html` is a jQuery method, is it defined?
    console.log(this.innerHTML);  // only have vanilla methods
});

One thing you must remember is that `this` refers to your context.

`this` is NOT a jQuery object which means it will not have jQuery methods available on it.

How would we jQueryfy™ `this`?

$( '.topNewsPost' ).click(function(event){
                    v----- call jQuery and pass `this` to it
    var $this = $(this);  // now you can invoke jQuery methods, aw yiss

    $this.html('I LOVE PIG LATIN');

});

The convention of starting your variable names with a `$` helps people remember that the value referenced is a jQuery object.

 

Should you use it? Up to you.

this

Animations/Effects

goodies

Animations/Effects

Some animations can accept functions as arguments which are treated as a callback function.

 

This function is invoked after the animation completes.

$( '.topNewsPost' ).show(function() {
    // do something after you show
});

$( '.topNewsPost' ).hide(function() {
    // do something after you hide
});

Consider CSS3 Animations

Tools like SASS make CSS3 Animations very managable

For inspiration check out

codepen.io

Creating Elements

Pass jQuery a tag and you'll get a new HTML object created for you.

This object starts its life in memory until you append it to the DOM

var newDiv = $( '<div>' );

manipulate it with jQuery Methods and append!

var newDiv = $( '<div>' );
newDiv
    .addClass( 'topNewsPost' )
    .css('height', '100px')
    .click(function(evt) {
        alert('NEWS NEWS NEWS');
    })
;

$(document.body).append(newDiv);

Creating Elements

previous code

var newDiv = $( '<div>' );
newDiv
    .addClass( 'topNewsPost' )
    .css('height', '100px')
    .click(function(evt) {
        alert('NEWS NEWS NEWS');
    })
;

different way

var newDiv = $( '<div>', {
    class: 'topNewsPost',
    css: {
        'height': '100px'
    },
    click: function(evt){
        alert('NEWS NEWS NEWS');
    }
});

XHR stands for XML HTTP Request

AJAX stands for Asynchronous Javascript and XML

Basically, you can request for data without having the user refresh the page or leave to another page.

 

It redefined the way we use the internet.

Advantages

  • Reduce the traffic travels between the client and the server.
  • Web application "feels" faster because the browser has less data to process

Disadvantages

  • Pages that rely heavily on XHR Requests for fetching and then displaying data will not indexed by web search engines.
  • can seem complex to beginners

Syntactic Sugar!

An Example of a GET request


//           v-- where to request for data
$.get( "ajax/test.html", function( data ) {
                                 // ^-- data coming back from the request

  // do stuff with your data!
  $( ".result" ).html( data );
  alert( "Load was performed." );
});

Syntactic Sugar!

An example of a POST request which sends data along with the request

var dataToSendToServer = {
    username: 'KingtakMF420',
    newBlogPostHeader: 'TODAY WAS A GUUD DAY',
    newBlogPostBody: 'NAH FOREAL DOUGH'
};

//        |-- where to request for data
//        V                 v-- send data along with your request TO the server
$.post( "ajax/test.html", dataToSendToServer, function( data ) {

  // do stuff with your data!
  $( ".result" ).html( data );
  alert( "Load was performed." );
});

Handling Errors and attaching Event Listeners for XHR Events

var jqxhr = $.post( "mysite.com/login", function() {
  alert( "success" );
})
  .done(function() {
    alert( "second success" );
  })
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "finished" );
});
 
// Perform other work here ...
 
// Set another completion function for the request above
jqxhr.always(function() {
  alert( "second finished" );
});

Resources

Anti-Resource?

jQuery

By Ray Farias