An Introduction To jQuery

jquery-logo

What is jQuery?

“A fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers”. [Reference: jQuery.com]

Basics

jQuery focuses on queries and a query is simply a CSS selector which identifies a set of html elements within your document.

Include jQuery

You need to include jQuery in your file. You can either download file from jquery.com and host it on your server or use CDN (Content Delivery Network) to link the file. Follow the link below to copy the Google’s CDN link

https://developers.google.com/speed/libraries/#jquery

which looks like

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>

Always place this link before the closing body tag of your html document

Pass a css selector string

Example:

Select all h1 headings in our page

$("h1");

Select all paragraph tags in our page

$("p");

jQuery object

(also known as jQuery result, set or selected elements)
A jQuery function returns a jQuery object. “A set of document elements returned by jQuery function”
Example

var n = ("p");
console.log(n);
Output:
[
	p.intro,
	p
	p#note
]

console.log function outputs to the developer’s console e.g, firebug and returned result is a jQuery object which is simply an array of html elements.

console.log(n.length); //3

will return the number of objects in an array.

console.log(n[0]); //p.intro

will return first item in the array.

jQuery Methods

Doing something interesting with a jQuery object

$("p").css("color", "blue");

Will change color of all of our paragraphs to blue using CSS method. Here we pass a “p” selector to our jQuery function and this returns an array of objects containing all our paragraph elements then using css method we change
the color of all paragraph elements to blue.

Change all paragraphs to red and italic

/*
//one way
$("p").css("color", "red");
$("p").css("font-stlye", "italic");

//another way
var p = $("p");
p.css("color", "red");
p.css("font-stlye", "italic");
*/
//the efficient way, separate property and value by colon
$("p").css(
		  {
			"color": "red",
			"font-style": "italic"
		  }
);

Change all h1 headings to blue and the text to “Hello”

//chaining is used
$("h1").css("color", "blue") . text("Hello");

 

 

Comments

comments

no responses for An Introduction To jQuery

    Leave a Reply

    Your email address will not be published. Required fields are marked *