William Liu

jQuery


Table of Contents

##SUMMARY

jQuery is a Javascript library that helps with manipulating HTML elements. So what does jQuery really do? jQuery is made up of:

####Basic jQuery Example

Sometimes it is easier to see code than to explain it. Here we have a div that has an effect of sliding down slowly. No one would ever use this, but the idea is that effects are easy to implement.

index.html

<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script type="text/javascript" src="script.js"></script>
        <title></title>        
    </head>
    <body>
        <div></div>
    </body>
</html>

script.js

$(document).ready(function(){
    $(#div).slideDown('slow')
});

##JavaScript Objects

####JavaScript Structure

For some quick background, JavaScript is filled with objects; a browser window, a document, variables, etc. Objects have properties that describe the object. Objects can perform actions called methods (can tell by the (), e.g. bark()).

Example of real world objects

Object Parts Actions
dog tails wag
dog head bark
car horn honk

JavaScript objects

Object Property Method
document title  
document url  
document   write()
window innerHeight  
window   alert()
str name length  
str name   split()

####jQuery Structure

The basic pattern to jQuery is selecting an object with $ and using a jquery method (e.g. mouseenter()), then applying another jquery method/action (e.g. fadeTo()) to that object.

// On mouseover, fade to 25% opacity fast
$(document).ready(function() {
    $('div').mouseenter(function() {  // select item with jquery function
        $('div').fadeTo('fast', .25);  // apply an action
    });
});

####Document Ready

An example of the javascript and jquery structure is loading a document. The idea is that a page can’t be loaded until the document is ‘ready’. jQuery detects this state; here we pass an anonymous function (although you can pass in named functions too) to run as soon as the document is ready.

// Passing in an anonymous function
$(document).ready(function() {
    console.log("ready!");
});

// Passing in a named function
function myReadyFn(jQuery) {
    console.log("ready!");
}
$(document).ready(myReadyFn)

If we break up the pieces, we can see what is going on behind the scenes in jQuery:

##jQuery Events

####mouseenter()

This produces a change when your mouse enters a HTML element.

// On mouseover, fade to 25% opacity fast
$(document).ready(function() {
    $('div').mouseenter(function() {
        $('div').fadeTo('fast', .25);
    });
});

####mouseleave()

This produces a change when your mouse exits a HTML element.

// On mouseleave
$(document).ready(function() {
    $('div').mouseenter(function() {
        $('div').fadeTo('fast', 1);
    });
    $('div').mouseleave(function() {
        $('div').fadeTo('fast', 0.5);
    });
});

####More jQuery events

There is a huge list of jQuery events which can be found here.

####Chain events

You can chain jQuery events like this example, where we click on id=’pull-me’ and it toggles id=’panel’.

$(document).ready(function(){
    $('.pull-me').click(function() {
        $('.panel').slideToggle('slow');
    });
});

##jQuery selectors

jQuery selectors can help select specific items, whether they are HTML elements, CSS ids, or CSS classes.

$('button')  // select by HTML element
$('#header')  // select by CSS id="header"
$('.removeme')  // select by CSS class="removeme"

For example, say we wanted to remove the fourth list item (identified by the CSS id=”removeme”).

index.html

<!DOCTYPE html>
<html>
    <head>
        <title>Simplify, Simplify</title>
        <script type='text/javascript' src='script.js'></script>
    </head>
    <body>
        <div> Remember!
            <ul>
                <li>
                    <ol>
                        <li>Start with the function keyword</li>
                        <li>Inputs go between ()</li>
                        <li>Actions go between {}</li>
                        <li id="removeme">jQuery is for chumps!</li>
                    </ol>
                </li>
                <li>Inputs are separated by commas.</li>
                <li>Inputs can include other functions!</li>
            </ul>
        </div>   
    </body>
</html>

script.js

$(document).ready(function() {
    $target = $('#removeme');
    $target.fadeOut('fast');
});

####Compound selectors

We can apply effects to multiple selectors through a compound selector

$('p, li').fadeTo('slow, 0);')

####This selector

If you want to select only a particular item, use this. For example, only this div fades out instead of all divs.

$(document).ready(function() {
    $('div').click(function() {
        $(this).fadeOut('slow');
    });
});

##jQuery variables

var fav_number = 7;
var first_name = "Will";
var p = $('p')

####Difference $p vs $(‘p’)

$p is just a variable name. $('p') is a funtion that creates a jQuery object.

##jQuery modifying HTML elements

With jQuery, we can not only modify existing HTML elements, we can also modify the actual structure of our websites in response to user actions.

####Create HTML elements

Here is a quick example of adding a h1 tag.

// Set $h1 variable to a text
$h1 = $("<h1>Hello</h1>")

####append(), prepend(), appendTo(), prependTo()

You can add HTML elements using append(), prepend(), appendTo(), and prependTo(). The functions with ‘To’ are basically the same, just a reversed order of what you specify.

#(".info").append("<p>Stuff!</p>");  // Add p to elements with class .info
#("<p>Stuff!</p>").appendTo(".info");  // Same, just specified differently

####before(), after()

You can specify where in the DOM to position an element with before() and after(). This lets us move elements around.

Basic example of after

$('target').after('<tag>To add</tag>');  // Basic format
$('#one').after('<p>Stuff!</p>');  // Example

Move elements around with after

var $paragraph = $("p");  // point to existing element
$("div").after($paragraph);  // move a div after paragraph

// Above code is the same as:
$("div").after($("p"));  // select existing element with $("p"), put div after

####empty(), remove()

We also have the ability to remove HTML elements from our document. empty() deletes the contents of an element along with all its descendants. remove() deletes not only the contents of an element and the element itself.

$("p").remove();

##jQuery modifying CSS elements

####addClass(), removeClass(), toggleClass()

You can add, remove, and toggle CSS classes with jQuery. Note that you are not selecting anything, just modifying your element to add a class so we do not need a # or . in front of the class.

$('selector').addClass('className');  // Basic Format
$('selector').removeClass('className');  // Basic Format

$(document).ready(function(){
    $('#text').click(function(){
        $('#text').toggleClass('highlighted');  
    });
});

####height(), width()

You can resize elements with height() and width().

$("div").height("100px");
$("div").width("100px");

####css()

You can modify specific css using a general purpose .css(), which takes in two inputs: a CSS element to alter and a value to set it to.

$("div").css("background-color", "#008800");

##Modify Content

You can also modify the contents of HTML elements using html() and val().

####html()

html() is used to set the content of the first element match it finds.

$("selector").html("contents");  // Example
$("div").html("I love jQuery!");  // Sets the contents of the first element match

####val()

val() is used to get the value of form elements.

$("input:checkbox:checked").val();  // Get first checked checkbox

var input = $('input[name=checkListItem]').val();  // get the value from an input

####on()

on() is an event handler that takes as inputs an event, its selector, and an action. This allows you to dynamically update the content of your HTML page.

$(document).on('event', 'selector', function() {
    //Do something!
});

$(document).on('click', '.item', function() {
    this.remove();
})

##jQuery effects

You can create animated effects with jQuery, some are simple like hide() and some are a bit more complex like animate()

####hide()

$(document).ready(function() {
    $('div').hide();
});

####focus()

You can use focus on html elements that take input (like a textarea or input).

$(document).ready(function() {
    $('#target').focus(function() {
        alert("Target is in focus!")
    });
};)

####animate()

$('div').animate({top:'+=10px'}, 500);  // move a div 10 pixels down in 500ms

##jQuery UI

For more advanced effects, look up jQuery UI. These have:

##ARIA

ARIA (aka Accessible Rich Internet Applications ) provides a way to add missing semantics (e.g. describe role of widgets in more detail) to assistive technologies like screen readers. ARIA makes use of the Accessibility API to connect the User Agent (i.e. browser dom, javascript) to Assistive Technology. The Accessibility API is split up into:

HTML example using the aria-checked property to declare the state of the menu items in a selectable menu. http://www.oaa-accessibility.org/example/25/

 <ul id="fontMenu" class="menu" role="menu" aria-hidden="true">
   <li id="sans-serif"
     class="menu-item"
     role="menuitemradio"
     tabindex="-1"
     aria-controls="st1"
     aria-checked="true">Sans-serif</li>
   <li id="serif"
     class="menu-item"
     role="menuitemradio"
     tabindex="-1"
     aria-controls="st1"
     aria-checked="false">Serif</li>
...

CSS example used to alter the visual appearance of a selected item using the aria-checked property.

li[aria-checked="true"] {
    font-weight: bold;
    background-image: url('images/dot.png');
}

JavaScript example used to update the aria-checked property.

var processMenuCHoice = function(item) {
    // 'check' the selected item
    item.setAttribute('aria-checked', 'true');
    // 'uncheck' the other menu items
    var sib = item.parentNode.firstChild;
    for (; sib; sib=sib.nextSibling) {
        if ( sib.nodeType === 1 && sib != item) {
            sib.setAttribute('aria-checked', 'false');
        }
    }
};