Saturday, May 28, 2016

Introduction to jQuery Library

What is jQuery

jQuery is a javascript library you include in your web pages.
jQuery allows you to select elements using a CSS-style selector and do something with those elements by calling a jQuery method.

Selecting HTML elements with jQuery

$('p');  /* a jQuery object */
  • $() works as short invocation to the jQuery() function
  • $() creates a jQuery object which stores references to the selected elements

Doing something with a jQuery object

A jQuery object has many methods you can call to perform an operation on the selected elements.

// get the content of the first section element
var htmlContent = $('section').html();
// set the content of each section element
$('section').html('having fun with jQuery');

Example: using the .html() method to set and get content

See the Pen EyxNoG by Massimiliano (@maxdesimone) on CodePen.

A matched set or jQuery selection

When you select an element, you get a jQuery object containing references to HTML elements. The jQuery object and its elements are called a matched set or a jQuery selection

  • if the selector matches one element the jQuery selection contains a reference to one element
  • if the selector matches multiple elements the jQuery selection contains references to each element
$('h1');  /* single element */
$('p');   /* multiple elements */

Storing a jQuery selection in a variable

If your code use the same jQuery selection more than once, it's convenient to save the object reference into a variable

  • when a variable contains a jQuery object, you give the variable a name beginning with a $ symbol
var $par = $('p.greeting');  /* $par refers to the jQuery object */

Looping through selected elements

When a selector returns multiple elements, you can update all of them with one method without using a loop

$('p').addClass('paragraph');  /* add the same class value attribute to each paragraph */

The ability to update all of the elements in a jQuery selection is known as implicit iteration.

See the Pen Looping by Massimiliano (@maxdesimone) on CodePen.

Method Chaining

If you want to use multiple methods on the same selection, write them one after the other in list separated by dots.

$('section p').fadeOut(2000).delay(1000).fadeIn(2000);

See the Pen jQuery method chaining by Massimiliano (@maxdesimone) on CodePen.

No comments :

Post a Comment