JQUERY: Basics



What is JQuery?


JQuery is a lightweight syntax for accessing JavaScript capabilities within a web page. The JQuery library takes more complex JavaScript code and wraps common tasks into methods that can then be called with a single line of code. Some of the simplified tasks include HTML/DOM/CSS manipulation, AJAX request and result handling, effects, animations and event handling.

Accessing JQuery


JQuery is an external library that needs to be included in each web page that uses its functionality. There are two schools of thought on how to do this. First, programmers can download (http://jquery.com/download/) and locally store a version of the library to include. The pros of this approach are that you can develop without a web connection and that you have control of where the library is. The big con of this approach is that the library can take some time to load and new users to your site will have to wait for it to download. The second option is to connect to a CDN (content delivery network). JQuery hosts one, as does Google. It is more beneficial to link to the Google version as many sites use this CDN, thus reducing download time due to a user's web cache. The Google JQuery CDN can be included into a web page using the following code:
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>

This link is often added at the end of a page's code to lessen the loading time necessary for the page content. However, this means that all JQuery scripts must be placed below this include to be effective.

JQuery Selectors


While JQuery is a JavaScript library, it has some special syntax that needs to be learned. The syntax is designed to help developers access an element and apply an action to it. The basic syntax for implementation is:
$(selector).action()

The $ sign helps identify the code as JQuery. The selector is how the element to be selected is identified. Selectors include:

Events


There are a variety of events that can be called from the above selectors. The most common events include: It is common practice to hold all JQuery actions until the entire document has been loaded. For this reason, all JQuery code is typically contained in the following structure:
$(document).ready(function(){

});

Notice the use of the anonymous function inside the ready event. This is common practice in JQuery.

Actions


Other actions that are available in JQuery include:

Putting it all Together

Assume that we have the following html code:
<div id='test'>This text is black.</div>

To change the text to blue, we would write the following JQuery code:
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js'></script>
<script>
	$(document).ready(function(){
		$('#test').click(function(){
			$(this).html("This text is now blue.");
			$(this).css('color', 'blue');
		});
	});
</script>