Learning JQuery – The Statement Structure

Welcome to the first in a new series of blogs that I am writing as I attempt too learn how to use JQuery. For those of you that don’t know, JQuery is a JavaScript library written to make many of the more complicated tasks that you may encounter in JavaScript much easier. In this series of blogs, I will be following along with a JQuery tutorial created by W3Schools.com, to learn what JQuery is and how to use it. Follow along as I do my best to describe JQuery as I come to understand it.

In this post, we are going to look at the basic structure of a JQuery statement. Look at the code shown below:

$(document).ready(function(){
$(“p”).hide();
});

In this code, you can see that JQuery statements follow the following format: $(SELECTOR).ACTION(). The SELECTOR is the element or elements that you are targeting, while the ACTION can either be an EVENT or an EFFECT. Events are actions that take place within a browser window such as the page loading, or a button being clicked. Effects are changes that are made to the target that was selected such as disappearing.

You will notice in the previous code that it is also possible to embed multiple JQuery statements within other JQuery statements using function prototypes: function() { }. In the previous example, the hide() effect is embedded within a ready() event. This is done so that the hide() effect won’t happen untill the page is ready (or loaded). This is important because until the page is loaded there will be no “p” elements to hide. It is a good idea to make use of the ready event whenever you work with JQuery on a web page.

Alternatively, you could use the following code to accomplish the same thing. Which style you choose to use to keep your code from executing before the page is finished loading is entirely up to you, but I prefer the longer previous example as it conforms to the basic syntax you will need to follow when using JQuery.

$(function(){
// jQuery methods go here…
});

Returning back to the example that was given in the beginning of this post, the code could be translated into English to say “Target the document and when that document is ready, do the following: target all p elements and make the p elements hide.”.

To make use of JQuery in your websites just remember to form your statements as we described before: $(SELECTOR).ACTION(). If you need to put statements within other statements, such as when you use an event, use a function prototype.

For more information on Jquery and to download it for your projects, be sure to visit the official website: https://jquery.com.

References

W3Schools.com. (2016, January 30). jQuery Syntax. Retrieved from http://www.w3schools.com/jquery/jquery_syntax.asp.

Leave a Reply