jquery

Readings

    • Severance, C. 2015. John Resig: Building JQuery. Computer, 48(5), 7-8. (ncsu)

Purpose

    • To shorten the number of lines needed to do basic stuff like: selecting an element, hiding content, etc.

    • To abstract away the different implementations of js in different browsers.

General information

    • One of many js libraries

      • Others: yahoo user interface library (YUI), Dojo, Mootools...

    • Widely used

    • Free

    • Large community

    • Plug-ins (extensions) to improve jquery functionality

References

Connecting it to your site/program

    • Hosted elsewhere (CDN)

      • By Google, MS, jQuery.org....

      • Goods and bads

        • Can't work without internet

        • Saves your server some time

        • Likely cached already in client browser

      • How

        • Just reference one of these hosts in your header, e.g.:

          • <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>

    • Locally hosted

      • Goods and bads

        • Works when internet down

        • Your server does a bit of extra work

      • How

        • Download jquery at http://docs.jquery.com/Downloading_jQuery.

          • Uncompressed lets you see source: good for learning but not in practice

        • Reference it in header, e.g.:

          • <script src="js/jquery-1.6.3.min.js"></script>

Pointers

    • Making sure that the page (DOM) is completely available:

      • Use the $(document).ready() function, which executes passed code after the page download is done.

    • Make sure to connect to jquery before you reference any of its code

    • Make sure to complete any CSS styles referenced by your jquery, before that referencing jquery

Selecting page elements

    • The jquery object lets you use CSS selectors, e.g.

      • $('#banner') selects the element with the ID banner

      • $('a') selects all the a elements

      • $('.submenu') selects all the elements with class submenu

      • Also, descendent, child, adjacent, and attribute selectors exist

    • Many of these will return sets of elements. You can filter these

      • $('.striped tr:even') selects the even elements of the tables with class striped

      • $('p:first) selects only the first p element

      • $('p:last) only the last

      • $(a:not(.navButton)' a elements that aren't in the navButton class

      • Also:

        • has(): contains another selector

        • contains(): has certain text

        • more...

Doing stuff with selected elements

    • Automatic looping: any method you apply to a returned list of selected elements is applied to all of them

    • Chaining: rather than several lines of code, you can append several methods, e.g.

      • $('#popUp').width(300).height(300).text('Hi!');

      • You can line break between these if you like

      • This is faster than doing multiple queries

    • Getting and replacing content

      • html: gets and sets html inside the selected elements

      • text: gets and sets the text (no tags)

      • append & prepend

      • before & after: just before (outside) or after the selected elements

      • remove

      • replaceWith

    • Working with tag attributes

      • addClass, removeClass

      • toggleClass: remove if there, add if not

      • attr(): gets or sets a tag attribute

        • e.g. var myUrl = $("#myID").attr("href");

        • $("#myID").attr("href","http://google.com");

      • removeattr()

    • Working with CSS properties

      • css: gets and sets current CSS property value, e.g.

        • css('background-color')

        • css('font-size', '200%');

    • Doing stuff on each item in a list

      • Use the each() function

        • $('.myclass').each()

      • Pass an anonymous function to it (function object)

        • $('.myclass').each(function() { /* js code */ } );

      • To refer to the current list item, use $(this)

        • $('.myclass').each(function() { $(this).html('<p>my text</p>'); } );

        • Note that while this also works, it refers to dom elements, not jquery elements, on which all the jquery magic works.

Handling events in jquery

    • Event types

      • Mouse events: click, dblclick, mouseup, mousedown, mouseover, mouseout, movemove

        • hover: combines mouseover and mouseout

        • toggle: pairs click events for toggling

      • Document/window events

        • load: when the page is done loading

          • Note that loading may continue long after the page is displayed, so it may not seem very responsive

        • resize, scroll

        • unload: when you leave the page

          • Use this to clean up when leaving page

      • Form events

        • submit: when the form is submitted

        • reset: return to default form settings

        • change: some fields notify when the user changes them, e.g. radio buttons

        • focus: whenever a new field gains focus

        • blur: "anti-focus" - when you leave a field to focus on another

      • Keyboard events: keydown, keyup, keypress

    • Handling events

      • IE8 and less handle events non-standard, so jQuery a big help here.

      • Basic jquery programming pdgm

        • select some elements

          • Here, you decide which element's events you're worried about

        • assign an event

          • E.g. $('.myclass').mouseover(); generates events whenever viewer mouses over your myclass elements.

        • pass a function

          • E.g. $('.myclass').mouseover(myMouseoverFunc); calls previously defined function myMouseoverFunc whenever user mouses over a myclass element.

          • You can also pass an anonymous function

      • Event information object

        • Is available in a returned object

        • Access it by including a parameter when you pass a function to an event

          • e.g. myMouseoverFunc(evtInfo)

        • Includes

          • pageX,pageY: browser relative mouse coordinates

          • screenX,screenY: monitor relative mouse coordinates

          • shiftKey: if shift is pressed

          • which: code indicating which key pressed

          • target: which element generated the event

          • data: information passed to the event handler

      • Controlling the default event behavior

        • E.g., whether or not to follow a link

        • To prevent

          • Call preventDefault() on event information object

          • Or, return false in event handling function

      • Unassigning an event

        • On element, call unbind('event type');

        • e.g. $('a').unbind('mouseover');

      • Keeping events local (stopping "event bubbling")

        • Events are also passed to dom ancestors

        • To stop this, call stopPropogation() on the event information object

      • Bind: handling multiple events with one function and passing data to that function

        • e.g. $('.myclass').bind('click',myInfo,myEvtHandler);

        • myInfo is a js object with lots of properties in it

    • Improving event responsiveness on page load

      • You need to wait until page loads to ensure dom is there before your code runs

      • But waiting for the load event can be confusing:

        • User sees page without js while page loads

        • Page finishes loading, suddenly js changes everything

      • Put your code inside $(document).ready() instead

Animations and effects

    • Effects

      • Types

        • To hide and show a jquery selection: hide(), show(), toggle()

        • To fade in and out: fadeIn(), fadeOut(), fadeToggle(), fadeTo()

          • fadeTo fades to a specific opacity. Fading to 0 doesn't free the element's space.

        • To slide in and out: slideDown(), slideUp(), slideToggle()

          • Down appears from top, Up disappears from bottom

      • How effects happen

        • Speed of effect: pass a speed parameter

          • 'fast', 'normal', 'slow'

          • or a number of msecs

        • Easing, or change in velocity of the effect

          • Pass as second parameter

          • 'swing' is the default: slower at beginning and end

          • 'linear': no easing, that is no change in velocity

          • other non-standard effects possible with Easing plugin (e.g., bounce)

      • Note that when an element disappears, it is still in the DOM

    • Animations

      • You can animate the properties of an element over time

      • To do this, call animate(), and pass

        • The CSS properties you wish to end up on

          • absolute: e.g., {left: '100px'} will move to 100 pixels from page left

          • relative: e.g., {left: '+=100px'} will move 100 pixels from current position

        • The time over which you want to animate

          • e.g., 1000 is 1000 msec or 1sec.

        • Easing parameter

      • Note you need the jquery Color plugin to animate color

    • Callbacks

      • You can execute code on effect or animation completion by passing a callback

      • Usually the last parameter of the effect/animation

      • This is one good way to run effects/animations in sequence rather than in parallel