Fundamentals of jQuery Tutorial

Welcome to the fundamentals of jQuery tutorial offered by Simplilearn. The tutorial is a part of the JavaScript Certification Training.

Let us begin with the objectives in the next section.

Objectives

In this fundamentals of jQuery tutorial, you will learn -

  • What Is jQuery

  • How to install jQuery

  • What a Syntax is

  • What Selectors are

  • jQuery Events

  • When A Key Is Pressed

  • jQuery Effects

  • Callbacks in jQuery

  • .html()

  • Changing CSS in jQuery

  • jQuery Animations

  • Attributes in jQuery

  • jQuery.Ajax

Let us begin with what is jQuery in the next section.

What is jQuery?

jQuery is a javascript library. There are many javascript libraries, such as Moo Tools, Scriptaculous, Dojo, Prototype, and many more. The reason to learn about jQuery over other great libraries is due to its simplicity and flexibility.

jQuery allows us to animate elements, add/remove classes, attributes, id’s, etc. It also allows us to use Ajax in a very simple way. It is the most popular javascript library for a reason. The best part is that when you execute some jQuery, it will run the same way in all five major browsers.

Whereas, normal JavaScript sometimes acts up, for instance, as in the internet explorer. In an internet explorer, we have to run that extra code when trying to make an ajax request. Whereas with jQuery, it does it for us.

It is automatically cross-browser compatible, it means that jQuery will make sure that it works in Opera, Internet Explorer, Firefox, Chrome, and Safari. A great feature of jQuery is the documentation, it is easy and has many examples. For any related questions, jQuery.com provides solutions.

Let us learn in brief about the options available on the website jQuery.com.

In the website jQuery.com, you will be able to download jQuery. On clicking the documentation icon on the website, you will be guided to the documentation page. The documentation page contains references including, Selectors, Attributes, Traversing, Manipulation, CSS, Events, Effects, Ajax, Utility, jQuery UI, jQuery core concepts.

It also provides tutorials on how it works and support. The selectors' support that is provided, can be used to select anything. The all selector contains the animated selectors, the name, the value. The documentation provided is phenomenal and well organized.

There is a lot of help available.

We will just learn the basics of jQuery right now, like in the selectors we will look into some of the animations, the effects, manipulation of CSS. We will not go deep into jQuery as it is vast, instead of on completion of the jQuery module, we can log into jQuery.com and look at the different things that can be done using jQuery.

Now, let us learn about the syntax and how to install jQuery into a web page.

Installing jQuery

Installing jQuery is actually easy. We can either download and install the file using all of jQuery on our own website - where we do not need to rely on another server to host it.

OR

We can link to a hosted jQuery file from a CDN host (Content Delivery Network) such as Google or jQuery.com or even Microsoft.

Downloading jQuery

If we choose to download jQuery we have to first go to www.jQuery.com/download/, and to download jQuery, we have a couple options. We can select the “Production” or the development option and then click the download button.

The first option is the“Production” option, which means that the code has been minified. When we say that the code has been minified, it means all the white spaces and comments have been taken out of the code so the file is much smaller. Usually, it is about 32 kbs.

The other option is, “Development”, which is uncompressed. This is often over 247 kbs. Even if you have a fairly fast internet to run the Development code, we still want to reduce the load time. For this, we make use of the Production (minified) code.

Once you choose what to download, click the download button. You will then get directed to a page containing the code. Right-click anywhere on the page and select the “Save as..” option and save it to the folder where your website (and pages) are located.  

Using a CDN

CDN stands for Content Delivery Network, which is a network that some companies host so that you can access their content easily and reliably.

For example, Google has jQuery on their CDN. Because jQuery updates often, we aren't going to use the jQuery version that is available as this video is being made.

To use CDN, click the link, www.jquery.com/download/ , and click one of the three links available on the left, which is usually Google Ajax Libraries”. “Microsoft CDN”, or “jQuery CDN Minified or Full.” Clicking on either of them will bring up a page of code. In this case, we can make use of the code by copying the URL instead of having to right-click and selecting the “save as…” option.  All three code options are extremely reliable and so it doesn’t matter which copy you use.

Installing jQuery

jQuery installation is easy. Let us look at the installation process in steps.

Step 1:

In order to add our javascript files to our site, we used the <script></script> element like-

<script src= “directory/javascriptFile.js”></script>

Step 2:

All we have to do is change the source or the ‘src’. If we made use of Google, Microsoft, or jQuery’s CDN (Content Delivery Network), we just copy that link into our source. The code would look like -

<script src= “// ajax.googleapis.com/ ajax/ libs/ jquery/ 1.8.0/ jquery.min.js”></script>

/* Or the Microsoft CDN */

<script src= “http:// ajax.aspnetcdn.com/ ajax/ jQuery/jquery-1.8.0.min.js”></script>

Step 3:

If you download jQuery, change the src to filename. Example:

<script src= “jquery-1.8.0.min.js”></script>”>

All these <script> elements should be put inside the <head> of your page.

On completion of the installation of jQuery, we will next learn how the syntax works. It is a little different than what we have seen before, but it will make sense once it is all broken down.

Syntax

The syntax for jQuery looks pretty strange in some cases. Before we learn about selectors and events, animation or even ajax, we need to know how the syntax works.

Let us look at the code snippet written inside the head section.

<head>

<script src=”jquery.js”></script>

<script>

$(window).ready(function() {

Alert (‘Loaded’);

 });

</script>

</head>

If we run this code on our webpage, it should load the page and immediately run the alert() function. If that works, the jQuery was installed properly. Now that we have the code tested, we need to make some sense of what we saw above.

the dollar sign($) is the function to select something. It is similar to :

function $ (id) {

return document.getElementById(id);

}

From the code line shwon in the image, we have -

  • window - The window is the selected object. This means that jQuery is selecting the entire window.

  • .ready() - The .ready() method executes the specified code when the window is ready to start using jQuery.

  • function( ) { - Inside the “ready( )” method, we have “function( ) { “ which allows us to put a large block of code inside the ready( ) method.

  • alert (‘Loaded’); - The alert (‘Loaded’); is the code we can put inside the ready() method, and it will run as soon as jQuery is done loading.

  • }); - The “ }); ” on the last line, is the closing curly bracket from our function () { and the closing bracket from the ready( ) method, ended with a semicolon.

If we break this down even farther and space out the above code, it looks like this -

$(window).ready (

Function ( ) {

 // the code in here

}

};

This is a very common syntax for jQuery. A selector using the $ function, an event such as ready ( ), our code inside the function( ), and the closing syntax together (back to back) which looks like “});”. This will seem very familiar in the near future.

Selectors

Earlier, we learned how to use “$( )” (the dollar sign function) in jQuery to select the window object. One of the very powerful tools that jQuery offers is how it can select elements.

First, we will see how we construct by id.

By ID

jQuery and select elements by ID, just like using the document.getElementById( ) method. But now, we have to be more specific. When we want to select an ID, it is like selecting an ID in CSS - we need to add the # sign character in front of the ID name.

jQuery

HTML

var MyID = $(“#elementID”);

<div id = ‘elementID’></div>

So here, we have the jQuery and the HTML. In the jQuery code, we just have the variable MyID is equal to the dollar sign, opening, and closing parentheses, apostrophes (or if you like you can use a quotation mark). This is how we tell jQuery what exactly we want to look for.

Next, to select the <div> ID of an element, we must use the number sign in front of the selector. From there we can modify the element ID anyway we like using JavaScript.  

Next we will discuss selecting by class.

By Class

With class, we can select more than one element at a time. To do this, just like CSS, we use the period in front of the to-be-selected class.

For example, consider the below code -

jQuery

HTML

var allBolds = $(‘.bold’);

<style>

.bold { font-weight:bold; }

</style>

</head>

 

<body>

<span class = ‘bold’>test</span>

<div class = ‘bold’>another test</div>

….

From the above code, we see that in a jQuery, we have the variable allBolds, which is equal to our selector.

As seen from the jQuery code, we have changed the # to a period ->.

The var allBolds = $(‘.bold’); now holds power over 2 elements, both the <span> and the <div> elements in the HTML.  

By Element

If we don't want to select something by its ID or class, we can also select by its element and this is also quite easy. This also follows the same rules as CSS does, where, we have the variable, the body and the variable name doesn’t matter.

Let us look at the code to understand.

jQuery

HTML

var theBody = $(“body”);

<!DOCTYPE html>

<html>

<head>

</head>

 

<body>

</body>

</html>

This will select the <body></body> element. var theBody now has full control over the <body> element.

By Attribute

Now we can also select by attributes. With the attributes selector, we have many options available. We can select the value of an attribute that starts with whatever we tell it to match, it can select a value that is equal to or not equal to exactly what we tell it to look for.

Here, we will focus on the “is equal to” selector.

Let us understand from the example below. Here, we have a query variable. All names are equal to our selector.

jQuery

HTML

var allNamess = $(‘[name=”testName”]’);

<span name=”testName”>Span 1</span>

<span name=”testName”>Span 2</span>

In this example, var allNames has power over 2 <span> elements because the name = “testName” in both <spans>

If you find that the selectors don't work when you try them, and you are sure that they are correct and they should work, you might need to put them inside the ready( ) method.

The reason why we have to let the window load and check to see if it is ready to execute any of the javascript is because the browsers were trying to load the selectors or jQuery before the actual jQuery code is done loading. This, as a result, becomes a problem as the javascript is trying to execute a particular function such as the selector function.

However, that function has not been defined, so it is trying to use jquery, but there is no jquery to use yet, as it is not fully loaded, so the solution to this problem, is to use the window selector, the ready() method, function() as shown in the code below.

$(window). ready(function( )  {

  /* We told the browser to not load this until jQuery is finished loading. */

var getBoldClass = $(“.bold”);

});

jQuery is a javascript library. It allows us to write a much powerful code without writing much code. And in the long run, it actually turns out to be a lot more convenient and a lot less code in what javascript would be.

Events part 1

There are many ways to handle events in Javascript. An event is something that happens, like in HTML where we have onclick or ondblclick attributes, we have similar events in javascript. However, with jQuery, we can eliminate the use of those event attributes and allow our javascript to automatically listen to our actions.

Not like a spy, but for when an event is triggered. We are going to cover a lot of different events since many of them can and probably will be used very often. Let us first look at Focus.

Focus

Let us recall what focus and blur are -  

Focus: Focus is when you click on and you activate an element such as the text area.

Blur: Blur is when you unfocus or you unclick or you move away from the focused element.

To create a focus event in jquery, we write our code as shown below -

jQuery

HTML

$(“textarea”).focus(function( ) {

$(“textarea”).css (“display”, “none”);

});

<textarea placeholder= “click in me”>

</textarea><br  />

<input type= ‘text’

Placeholder = ‘click in me’  />

Here, it says clicking me and click in me for both the input and the text area. What the code says that we are going to do here is, when we focus in on every text area it is going to change its CSS, it's going to change its display property to none, which means it's going to make it invisible so we click it, it just disappears and there's nothing we can do to get it back unless we use more jquery or javascript.

Whereas, when we click on the input in here, it is not going to disappear because, we have specified that this should only happen to text areas. If we have more than one text area it is going to get back all of them. If we want it to affect the one text area, then we must add “ID” in the line “ $(“textarea”).css (“display”, “none”); ” which will then become “ $(“textarea#textID”).css (“display”, “none”); ”

The function inside the .focus() event, which is - “ function( ) { $(“textarea#textID”).css (“display”, “none”} ” . It will run every time we focus on the text area. That is one way of using the .focus() event. We can also use it without the function inside of it. If we use it with no function inside, we are telling the users browser to automatically focus on something.

jQuery

HTML

$(“#focus”).click(function()  {

$(“#input”).focus();

<button id= ‘focus’>Button</button>

<input id=’input’  />

The .focus() event, with no function, as seen from the example, will focus on the text area when the button is clicked. That is, it focuses exactly on what we tell it to do. In this example, we used the .click( ) event as well.

Blur

To blur means to unfocus. And it is also used on elements that could be activated or selected.

jQuery

HTML

$(“#inputThenBlur”).focus(function( )  {

$(this).blur();

});

<input type= ‘text’ id= ‘inputThenBlur’   />

This

When we are writing code inside an event in jquery, we use $(this) to reference the selector.

$(“element”); ->  $(this) inside an event

$() is similar to:

function $(id) {

document.getElementById(id);

}

We can use this to manipulate parts of the DOM like the elements innerHTML by writing:

function $(id) {

document.getElementById(id);

}

$(“DivIDs”).innerHTML = “New HTML inside this Div element!”;

Displays:

New HTML inside this Div element!

Well, the $(this) selector is the same thing, but only works inside an event and will refer to that exact element. We will understand it better when we use it often.

Hover

The .hover() event accepts 2 functions. The first is the onMouseOver function and the second is the onMouseOut function. The syntax looks like this:

$(“selector”).hover(

function() {

/* The effect to take place when the mouse is over the element */

},

function () {

/* The effect to take place when the mouse is NOT over the element anymore */

}

);

Between the two functions is a comma to separate them just like how we separate parameters. You can think of .hover() as a function with 2 parameters. However, these parameters must be in the form of a function.

Let us go ahead and make this work now:

$(“div#demo1”).hover(

function() {

$(this).css(“border”, “1px solid red”);

},

function() {

$(this).css(“border”, 0);

}

};

Hover the mouse over me!

We will cover .css() eventually. For those who can’t wait:

.css(cssProperty, cssValue);

Keys

There are three events group together in this section, they are -

  • .keydown()

  • .keeppress()

  • .keyup()

They all behave the same way. The difference observed is when the code is executed.

Keydown:

  • When the button is being pressed down.

  • The HTML Attribute: onKeyDown= “”

Keyup:

  • When the button is being pressed down.

  • HTML Attribute: onKeyUp= “”

Keypress:

  • Key press this is the action of keydown and keyup together so when you press down and you lift up your finger from that particular key that is key press.

  • HTML Attribute: onKeyPress= “”

For the sake of simplicity, we will use a key press in this example. However, if you want to, you could switch out key press or key up and this will work the exact same way for all three.

$(“#demoTextarea”).keypress(function() {

Alert (“Key was pressed!”);

});

Next, we have Mouse.

Mouse

There are 7 mouse events. Every single one of them can be used in the same way as the example that will be given below. But first we need to know what the seven events are:

First Event

.mousedown() - First, we have the mousedown

  • This is when you click your mouse down but you do not release it yet.

  • The HTML attribute is onMouseDown= “”

Second Event

.mouseup() - Next, we have mouseup.

  • When you release the mouse from clicking, that is when we click down and then when we click up, this is what mouse up is.

  • HTML attribute is onMouseUp= “”

Third Event

.mouseover() - Then we have mouseover.

  • This is when you move your mouseover an element

  • HTML attribute is onMouseOver= “”

Fourth Event

.mouseenter() - Then we have most enter.

  • This is when your mouse enters an element.

  • This is similar to mouseover, but it's not quite the same, and there is no similar HTML attribute for this.

Fifth Event

.mouseleave()

  • This is when your mouse leaves the entered area

  • mouseenter and mouseleave usually work together, hand in hand

  • Even here there is no HTML attribute.

Sixth Event

.mousemove() - Then we have most move

  • This is when your mouse is in the targeted element, and it moves.

  • HTML attribute is onMouseMove= “”

Seventh Event

.onmoueout() - This is when your mouse moves out of an element

  • This is often used with .onmouseover() .Therefore, if we move our mouse over something we put in our mouse over it, or almost over. When we remove our mouse from that element, it is now moving the onMouseOut.

  • Thus, the HTML attribute for that is onMouseOut= “”

As an example, we can write -

$(“#mouseEvent”).mousedown(function()  {

$(this).append(“Mouse Down. ”);

});

$(“#mouseEvent”).mouseup(function()  {

$(this).append(“<b>Mouse up.</b>”);

});

Note: Technically, .click()  .dblclick() .focusin() .focusout()  .hover() & .toggle() are all mouse events, along with the mentioned ones, that is, the seven, plus all of these.

Toggle

Toggle is a very useful event. It allows us to hide and show elements instantly, and it allows jQuery figure out the css status. This means: if an element has display: none; then jQuery will make it show up.

And if the element has display: inline; or block or it is your showing up and its display basically is not none, then it will hide this element.

Let us understand this with an example,

jQuery

HTML

$(“#buttonToggle”).click(function()  {

$(this).next().toggle();

});


 

<button type= “button”

id= “buttonToggle”>

Click me

</button>

<span>I will be toggled!</span>

jQuery allows us to add events on our page without having to display it in our HTML source. Therefore, if someone looks at our page, they won’t see any onMOuseDown or onClick attributes in any of our tags.

Events part 2

Let us now explore more about Events.

Click

We have learned about the click in a couple of examples in the earlier sections. This event is very important. Without the click, a website would be a lot less interactive. Most people, when they want interactivity, will click on something on that web page.

For example, when you want to interact with a video, you click play and the video starts playing.

Also, most other people dislike it when the webpage tries to be interactive without their consent (eg: Popups, Tutorials on how to use the website, What’s new on the site, or even just videos that automatically start playing such as advertisements).

To solve this problem, we use the .click() event. The syntax looks like:

$(SELECTOR).click(function() {

/* Code in here.

Typically more jQuery goes in here. */

});

Example

$( “#elementID”).click(function() {

$(“input#name”).focus();

$(“input#name”).css(“border”, “3px solid black”);

});

Without the .click() event watching the <button>, we would never be able to focus on the <input/> section without confusing or annoying the user. But if the user decides to click it, and then something happens that they have already expected, then they will not be annoyed and confused.

Also, confused users often leave your website because they don't know what's going on or their attention has been kept on the page.

Double Click

Like most of our events, double click also has the same syntax as the .click() event. The difference is that the user has to click twice on the selected element in order to trigger the function.

$(“button#dblClick”).dblclick(function() {

Alert (“Double clicked!”);

});

This isn't used too often mostly due to the fact that users now want to interact with websites but they want to use minimal amount of effort possible, so most people just click once.

Submit

We can tell a form to submit using the .submit() method. We would usually use this after using javascript or jquery to validate some information from a user who filled out a form of ours. Instead of having a button in the form that has type= “submit”, we can change that to type= “button”.

We can then add an event such as .click() and validate the information. If the information passes our validation, which is the filtering process, we can then submit the form for the user. As an example here, we have

<form method= ‘get’ action= ‘myform.html’ id= ‘form1’>

<input type= “input” id= “name” />

<input type= “button” id= “validate” />

</form>

<script>

$( “#form1”).click(function() {

// validate info from $(“#name”);

$(this).submit();

});

</script>

Therefore, from the example, as shown, we have replaced the submit button to a normal button and then we add some jQuery events. This might seem like a lot of work, especially when we use the <input type= “submit” />. But then, we won't be able to validate the information.

Also, note that this is not a full example of form validation. Form validation will actually take the value of every input that the user puts in. It will check it to see if the length is right; if there are spaces in there; if there shouldn't be spaces in there; if it is numerical or non-numerical.

There are a few more events to add to this. For all the events, you can go to-

http://api.jquery.com/category/events

This will give you a full list of all the events that are available in jquery.

When a key is pressed

Web developers often want to create a shortcut (shorthand method) for something. It could be changing the page, quickly bookmarking, or submitting a form when “enter” is pressed. We will learn how to do this in the next section. But first, we should know that all keyboard keys are coded as numerical values.

Script

First, we have the script.

$(SELECTOR).keypress(function(e) {

var keycode = (e.keycode ? e.keyCode : e.which);

/* use var keycode anyway you want. */

});

So a few things to remember is that the SELECTOR can be any element, it could be anything that you like; It could be a div, body, HTML, and all this will be listed into a certain element. It can also be an entire page like the HTML, body and that will be listed over the entire page.

We then have the function(e) after the .keypress event. That ‘e’ stands for event. Because, javascript already has a keyword called “event”, we use our own “e” and we just short handed that to ‘e’. The “e.keycode ? e.keyCode : e.which” line of code is written using the ternary logic. It is like a shorthand if/else statement.

Ternary Operator

The question mark in the code line ( “e.keycode ? e.keyCode : e.which”) is actually called the ternary operator and can be accessed which is accessed using the question mark. Before the question mark will be the ‘if’ part of the statement. If it returns true, it will use the code after the question mark; if it is false, it will use the code after the colon.

This can be well understood by the example shown below.

JS: if/else

JS: Ternary

if(1>5)  {

alert(“1>5”);

} else {

alert (“1<5”);

}

var num = (1>5 ? “1>5” : “1<5”);

alert(num);

The logic is good but it can be tricky. In order to find out what button was pressed, we can simply alert the ‘var keycode’ while the ‘textarea’ is selected. Which means, if we select our textarea, for every function and for every key press it will execute this function -

“function (e) {

var keycode = (e.keycode ? e.keyCode : e.which)

Alert (keycode);

}”

which is part of the code example of -

$(“textarea”).keypress(function (e) {

var keycode = (e.keycode ? e.keyCode : e.which)

Alert (keycode);

});

It will be easier if we know all the keycodes. But, we do not have to remember all the keycodes as most of them are actually pointless to remember. The few useful keycodes such as “enter” are remembered.

Codes

Learning some of the other keycodes using a chart is not the best way to learn the popular keycodes. If you need to use a particular key, use the javascript above and use “alert (keycode)” to yourself.

jQuery Effects

jQuery is well known for its effect and simplicity when it comes to executing them. Here, we will learn about “hide()”, “show()”, “fading()”, and “sliding()”.

Hide and Show

Using hide and show, we can select an element and instantly hide or show it. We can do this with both javascript or jQuery, but jQuery makes it a little easier. Let us first cover hide()

jQuery hide()

To hide() an element we use the following code:

$(SELECTOR).hide();

We select whatever we want to hide and we type .hide() and it will hide the selected element instantly. We can also change the pace at which it hides. You can give the parameter “fast” or “slow”, which is equal to 200 and 600 milliseconds. Alternatively, you can supply the hide() effect on your own time in milliseconds.

A few examples are shown below. Here, you select your element and just regular hide will hide it instantly.

$(SELECTOR).hide();             // Hides instantly

$(SELECTOR).hide(“fast”);    // Hides fast

$(SELECTOR).hide(“slow”);  // Hides slow

$(SELECTOR).hide(451);     // Takes 451 milliseconds to hide

If you select an element and use the regular “hide” parameter, then that element will be hidden instantly. If you have something selected and your parameter is fast, it will quickly hide it, but not instantly. So, you can actually see it fade away. When your parameter is slow, the element will hide slowly, instead of quickly starting to hide.

The higher the “millisecond”, the slower the effect happens. This means,

100 milliseconds = fast

900 milliseconds = slow

jQuery show()

show() is used the exact same way that hide() is used. However, show() will either show or unhide the element that is selected.

$(SELECTOR).show();             // Shows instantly

$(SELECTOR).show(“fast”);    // Shows fast

$(SELECTOR).show(“slow”);  // Shows slow

$(SELECTOR).show(802);     // Takes 802 milliseconds to show

Note: Don't forget about the .toggle() method. This will save you the hassle of writing in a function that hides or shows an element.

jQuery Fading

Next, we have fading effects. There are three options for fading -

  • .fadeIn()

  • .fadeOut() and

  • .fadeToggle()

All three of these effects are used in the exact same manner as of hide() and show(). Let us cover one of them right now as they are all used in the exact same way.

fadeEffects

The first parameter (duration/easing) is how long it is going to take and the second parameter is a callback.,

  • duration/easing is the “fast” or “slow” parameters. Numbers can be given instead as milliseconds.

  • callback is the function to execute once the effect has finished.

To fade an element out, we write the code like this -

$(“button#fadeMe”).click(function() {

$(“span#fadeOut”).fadeOut(712);  // 712 milliseconds to fade out fully

});

fadeToggle()

This wil fade your element in and out. So you don’t need to write a function to fadeIn and fadeOut an element. This will fadeIn the hidden element, and fadeOut the visible element.

jQuery Sliding

Sliding is used the same way as the fade effects are use. With sliding also we have 3 options -

  • .slideUp()

  • .slideDown() and

  • .slideToggle()

.slideUp() will hide your element while sliding it upwards.

$(“#slideUp”).slideUp(300);

We can also slide elements down and toggle slide them.

toggleSlide()

Toggle slide is when you want to hide elements and you want to use .slideDown() to show it again.

There are a few other effects that jQuery offers. To view them all go to http://api.jquery.com/category/effects/

jQuery Callbacks

When we talk about callbacks, we are talking about the optional function that we can run when an effect has finished running. The callback is the last parameter in every effect. The callback is always optional. Here is an example of how a callback looks when we use the .slideUp() effect.

$(“#elementID”).slideUp(3000, function() {

Alert (“Finished sliding up”);

});

The second parameter in the .slideUp() effect is a function() { } while the first program was an integer (the # of milliseconds to take while sliding up).

The jQuery developers were very considerate when creating the javascript library. They allow us to skip the first parameter if we don't want to use it. This means we do not have to tell any event to take a certain amount of time to run either “slow” or “fast” or a precise amount of milliseconds.

We can skip that and let the event run at its default speed and then we can write a callback.

$(“#SelectedElement”).click(function() {

$(“#SlidingElement”).slideUp(function() {

$(this).slideDown(3000) {

});

});

When we run the script above by clicking on the <button id= ‘SelectedElement’> it activated the .click() event. Inside this event, was our .slideUp() effect. We did not specify how long it should take to slide up, but we create a callback function in the form of a function.

Remember that the Callbacks are in the form of functions.

Not every fact needs to have a callback. Callbacks are, in fact optional. If an effect exists in your code, and you will not be using the callback, then you don't have to write a callback function code.

Also, callbacks are great for double checking to see if your effect is done running. This is a great method because the callback function won't execute if the effect has been written incorrectly, or it doesn't finish running, possibly due to an error or the fact that its just going to continuously run.

.HTML() Method

When we were working with just Javascript and not jQuery, we learned that we could change the innerHTML of an element.

You can do that by following the code given below:

document.getElementById(“MyID”).innerHTML = “New inner HTML”;

With jQuery, we have a shorter method for accomplishing this -

$(SELECTOR).html(“New inner HTML”);

And if we leave the parameter blank, we can get the current innerHTML.

alert($(“#MyID”).html());

Example

This example will change the current innerHTML of our element, then it will alert us with what is inside of it, all inside a .click() event.

jQuery

HTML

$(“button”).click(function() {

var MyDiv = $(“#MyDiv”);

MyDiv.html (“This text just changed!”);

alert(MyDiv.html());

});

<button>Change the HTML</button>

<div id = ‘MyDiv’>Old text</div>

Changing_CSS

jQuery makes Javascript simple. With jQuery, we can easily change the CSS of any element. But first, a quick reminder of how we did this with javascript.

In Javascript, we had to write document.getElementByID along with our ID name, followed by the style, our property name, and finally followed by the value. The code is given below.

document.getElementById(“MyID”).style.property = “value”;

Where the .style object is very important as it is attached to the ID of your element. Thus, this could be  

.style.color = “blue”;

Let us now look at the syntax in the next section.

Interested in taking up Javascript Certification Training? Check out our Course Preview!

Syntax

The jQuery syntax for changing the CSS of an element is actually very clean.

$(SELECTOR).css(“PROPERTY”, “VALUE”);

Let us look over an example in the next section.

Example

Generally, you will want to keep the changing of CSS inside an event. That's because people don't want web pages to automatically interact with them without the person first giving the web page permission to do so.

An example would be the .click() event.

$(“button#demo1”).click(function() {

$(this).css(“background-color”, “black”);

$(this).css(“border”, 0);

});

Also, notice that there are quotes around the strings, but no quotes around the “0” integer. That is because Javascript and jQuery do not need quotes around a number. Only strings (letters) need quotation marks around them.

Be careful when you're changing the CSS of a selector that happens to be a class or an element. If you were to select all the .bold classes and change the CSS, then it will affect all the elements that have that class.

The Same takes place with the elements. If you selected all the <div> elements, then you would change the CSS of all the <div> elements on that page.

Animations

In the last couple of years, flash websites have virtually disappeared due to javascript libraries such as jQuery. jQuery can create animations as long as there is a start and finish point. Although these animations are not nearly as exciting as the cartoons that you'll find on youtube.

But these animations allow us to create drop-down menus, sliding images, changing CSS, etc. Actually, changing the CSS is how we are going to create an animation.

In the next section, let us look at the syntax.

Syntax

The syntax is given as -

$(SELECTOR).animate (PROPERTIES, OPTIONS);

This at first seems like a very short and simple syntax and it can be as long as we keep our animations short and simple. Let us look at a simple animation in the next section.

Simple Animation

In this example, we are going to change the CSS using an animation. However, we are only going to change one CSS property.

$(“#box”).hover (

function() {

$(this).animate({width: “+=100”});

}

function() {

$(this).animate({width: “-=100”});

}

);

One major part of our code is to pay attention to the curly brackets inside the first parameter. We use the curly brackets to state that the parameter is an object or, in this case, a map which is similar to an object. Your first word does not need quotes, but the value does need quotes.

This almost looks like CSS than javascript and if we look at the width: “+=100” part. We will go over this object like the parameter or the map a little bit more when we get to a larger example. Also, know that only values with numerical properties can be animated. So, width will work perfectly fine in our example.

But if we try to animate the background color by using the code given below, we would fail. The reason for this is that computers easily cannot turn words into numbers and appropriately change the shades.

$ (this).animate({backgroundColor : “red”:});  

Options

The properties from the syntax is the CSS. The OPTIONS, which is the second property, are things like Duration, Easing, and Callback.

Below is the example that will change multiple CSS declarations, it will declare a duration in milliseconds, the type of easing, and the callback function.

$(“#box2”).hover{

function() {

// onMouseOver section; Hover In

@(this).animate (

{

width = 200

height = 200               //This is all the CSS

borderWidth: “10px”,

},

2500,                         // This is the 2.5 second duration

function() {                // This is the callback function

alert(“Finished animated-callback”);

}

};

},

function() {

// onMouseOut section; Hover Out

$(this).animate (

{

width = 100

height = 100             // This is all the CSS

borderWidth: “1px”,

},

2500,                       // This is the 2.5 second duration

function() {              // This is the callback function

alert(“Retun back-callback”);

}

};

}

};

What happened was that we created a .hover() event, and that needs 2 functions - one in each parameter. The first function( ) { } is the Hover In function, and the second function ( ) { } was the Hover Out function. In our first function, we said -

$(this).animate({PROPERTY: VALUE, PROPERTY: VALUE}, DURATION, CALLBACK FUNCTION);

If we break this down it doesn’t seem like a long piece of code. Inside the curly brackets is our CSS. Javascript doesn’t handle string values, only numerical values can be animated. In the example, we have used borderWidth instead of border. That’s because we need to stick with numerical values, and when you write the CSS for those, they turn out different.

borderWidth: 1px;

Border: 1px solid red;

The object-like parameter

As mentioned earlier, the first parameter is an object. Objects look like arrays with curly brackets and colons. What our example said was -

var firstParameter =

{

Width: 100,

Height: 100,

borderWidth: “1px”,

};

This object-like parameter is called a map.

jQuery Attributes

We can very easily access and change HTML attributes. To do this, we use the .attr(attrname, value), the first parameter is attribute name the second parameter is the value.

Let us look at accessing attributes in the next section.

Accessing Attributes

If we want to access an attribute’s value in any HTML element, we can write .attr(attrName) with no value is given so no second parameter and that will return the current value.

As an example, we have -

<div id= ‘DemoDiv’ title= ‘Test title’>

DemoDiv

</div>

<script>

$(document).ready(function() {

var divElem = $(“#DemoDiv”);

divElem.click(function () {

alert(divElem.attr(“title”));

});

});

</script>

div id is equal to ‘DemoDiv’, the title is equal to ‘test title’; and when we put the mouse over to DemoDiv it says Test title.

In the code we have, “$(document).ready(function() { ” so when the jquery is finished loading, it can execute the code inside of it; when it is unloading, we are going to assign variable divElem. To the divElem we will add a “.click” event, inside that “.click” event we have a function.

The work of the function() inside the divElem is to alert us with the divElem that is - “$(“#DemoDiv”)” . So we will then have the “title” present inside the attribute matching with the title Test title and the Demodiv inside the alert function matching that at div id.

To get the title, we wrote: $(SELECTOR).attr(“title”); and this will work with any attribute. So if we want to get that the elements name, we could just write $(SELECT).attr(“name”);. We will have to put this into a variable to actually use this value.

Thus, appropriately we can write:

$(document).ready(function() {

var elementName = $(“#DemoElement”).attr(“name”);

alert(elementName);

});

This code snippet will provide us with #DemoElement ‘s attribute name= “VALUE”. Value is what we will get in return.

Changing Attributes

We can change an element’s attributes or we can even set new ones if the current attribute does not exist. To change the attribute, we add a second parameter to the .attr() method.

<div id = ‘DemoDiv2’ title= ‘Test title’>

DemoDiv #2

</div>

<script>

$(document).ready(function() {

var demoDiv = $(“#DemoDiv2”);

demoDiv.click(function() {

alert (demoDiv.attr(“title”));

// we change the title here

demoDiv.attr(“title”, “changed title!”);

alert(demoDiv.attr(“title”));

});

});

</script>

When we click on DemoDiv #2 above, it alerts us twice. Once with the old title, and once with the new title. To change any attribute, or add an attribute if it doesn’t exist in that element yet we write -

$(SELECTOR).attr(ATTRIBUTE, NEW_VALUE);

Data

Next, we have the data, and this only applies to HTML5 browsers. Often, web developers want to store data inside an attribute and access it later. Whether PHP wrote the attribute and javascript is accessing the attribute, or javascript a storing the information in an attribute, both situations apply here.

The data-* and you can replace the asterisk with any sort of word that you like in there. So the data attributes are the custom attributes that web developers use. We can name it anything after the dash, which is the asterisk and we can access it very easily.

<div data-number= “2 3”> There is a number in here</div>

<script>

$(document).ready(function()

var MyDiv = $(“div”)script

MyDiv.click(function() {

var divNumber = MyDiv.data(“number”);

alert(divNumber);

});

});

</script>

You should note that, if there is more than one div, this will return an array. Remember to be specific; use id’s if you need to.

Being able to access attributes and store information in attributes will become extremely important as a web developer. By being able to access, or modify attributes, using javascript or jquery we can change how the page acts.

Javascript and PHP cannot talk to each other and that's because javascript as clients is thought as only worked on the browser and PHP a service only works on the server. However, javascript can change certain parts of a web page and when called upon, PHP can then pick up the newly changed attributes and this is one way that PHP and javascript can actually talk to each other.

Also, know that storing information in attributes, even if jQuery creates the attributes of the code so that it won't show up in the initial source code, this is not a secure way to store information. Never store information such as passwords, credit card numbers or anything else that's very sensitive in javascript/jquery, HTML, CSS, etc. They should always be kept on the server for extra protection.

jQuery.ajax

In Ajax, we dynamically load other pages into the current page without having to reload the page. All the code we write in the Ajax module just to get some tiny code from another page can easily be done in jquery. There's a lot to cover when it comes to Ajax and jquery and for now, we will cover the basics.

Note that Ajax does not work on local machines unless you are hosting a server. Ajax is javascript asking the server for permission to another file. If you don't have a server, then javascript can ask the server, which means, your Ajax is not going to work.

The local server that we generally use for testing the products before releasing them online is Webb. This work for everything that we need, locally. This is available at www.wampserver.com/en/ . We choose English and download it from there by just clicking the download button.

Ajax Load

Let us now look at the Ajax load. We can simply load a file, the issue with this is that the file we load will be loaded into the selected element.

We have,

$(SELECTOR).load(FILE);   // FILE could be something like “file.txt”

This will put the file inside the .html() of the SELECTOR. Below shows an example;

<div id= ‘ajaxMe’>Static text</div>

<script>

$(document).ready(function() {

$(“#ajaxMe”).click(function() {

$(this).load(“textFile.txt”);

})

});

</script>

This will work unless we want to harness the code that's inside of textFile.txt. In Ajax, we used the ajaxHandler.responseText, and that was our variable which held our Ajax page information. To do that, we need to use an actual Ajax call.

In the next section, we will see how to write the natural Ajax call.

Ajax

To write the natural Ajax call with jQuery it looks like this - $.ajax();

The dollar sign with just a period, in this case, just means jQuery.ajax, but in a shorthand method. Let us now look at this basic script.

$.ajax({

Url: “fileToLoad.ext”,

Success: function(data) {

// data is the variable that holds our information.

}

});

What this will do is find “fileToLoad.ext” and try to ajax it. Upon success, it will call a function with one parameter - data. This parameter holds our ajax information. All of this is set inside an object.

We can tell by the curly brackets that it contains the entire parameter and the use of object names with colons, all separated by a comma. These are technically called “maps”. Let us look at the Ajax script to execute it.

<button>Click me</button>

<div id = ‘ajaxDiv’>&nbsp;</div>

<script>

$(document).ready(function() {

$(“button”).click(function() {

$.ajax({

Url: “htmlFile.html”,

Success: function(data) {

$(“#ajaxDiv”).html(data);

}

});

});

});

</script>

This is the new HTML file and it is a plain file. No DOCTYPE is declared (although it is recommended). None of this HTML is in the <body> element. There is no <head> element, <title> or <html> element. Yet, this is still being styled by HTML and CSS.

This means any Ajax file we have we don't need to make it an official page. It doesn't have to be an HTML5 page because, all we want to do is grab the information whether it is an XML, just a text file, or HTML, possibly even just CSS and then we want to use that inside of our variable. In that variable, we can put it anywhere we like.

The $.ajax method is more powerful because of the options we are given, .load is faster for the web developer because we don't need to write all the options that we want. For more information on jquery.ajax() you can log onto http://api.jquery.com/jQuery.ajax/ and read their documentation. They are very thorough.

Summary

Let us now summarize what we have learned in this fundamentals of jQuery tutorial. We learned-

  • What Is jQuery

  • How to install jQuery

  • What a Syntax is

  • What Selectors are

  • jQuery Events

  • When A Key Is Pressed

  • jQuery Effects

  • Callbacks in jQuery

  • .html()

  • Changing CSS in jQuery

  • jQuery Animations

  • Attributes in jQuery

  • jQuery.Ajax

Conclusion

With this, we come to an end to the Fundamentals of jQuery Tutorial.

  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.

Request more information

For individuals
For business
Name*
Email*
Phone Number*
Your Message (Optional)
We are looking into your query.
Our consultants will get in touch with you soon.

A Simplilearn representative will get back to you in one business day.

First Name*
Last Name*
Email*
Phone Number*
Company*
Job Title*