Unit VI: Introduction to JQuery - Web Technologies I - BCA Notes (Pokhara University)

Breaking

Sunday, March 15, 2020

Unit VI: Introduction to JQuery - Web Technologies I

Introduction:

jQuery is a fast and concise JavaScript Library created by John Resig in 2006 with a nice motto Write Less, Do More. jQuery simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is a JavaScript toolkit designed to simplify various tasks by writing less code.

Introduction to jQuery, Why jQuery, Advantages of jQuery, JQuery fundamentals, Installation Process of jQuery, jQuery Syntax, jQuery Selectors, jQuery Events, jQuery Syntax For Event Methods, Commonly Used jQuery Event Methods, The on() method in jQuery,  Page layout using jQuery

Here is the list of important core features supported by jQuery:

1. DOM manipulation: The jQuery made it easy to select DOM elements, traverse them and modifying their content by using cross-browser open source selector engine called Sizzle.

2. Event handling: The jQuery offers an elegant way to capture a wide variety of events, such as a user clicking on a link, without the need to clutter the HTML code itself with event handlers.

3. AJAX Support: The jQuery helps us a lot to develop a responsive and feature-rich site using AJAX technology.

4. Animations: The jQuery comes with plenty of built-in animation effects which we can use in our websites.

5. Lightweight: The jQuery is very lightweight library - about 19KB in size (Minified and gzipped).

6. Cross Browser Support: The jQuery has cross-browser support, and works well in IE 6.0+, FF 2.0+, Safari 3.0+, Chrome and Opera 9.0+

7. Latest Technology: The jQuery supports CSS3 selectors and basic XPath syntax.

Why jQuery:

Introduction to jQuery, Why jQuery, Advantages of jQuery, JQuery fundamentals, Installation Process of jQuery, jQuery Syntax, jQuery Selectors, jQuery Events, jQuery Syntax For Event Methods, Commonly Used jQuery Event Methods, The on() method in jQuery,  Page layout using jQuery

1. Promotes Simplicity:

Most website developers find jQuery to be easy to learn and intuitive as the library is built using simpler and shorter codes. With its open coding standards and simple syntax, web designers can shorten the time that it takes to deploy a site or application. With jQuery, developers do not have to be expert web designers or programmers for them to come up with excellent styles for their websites. Web developers that have done some testing and coding of CSS files will appreciate the easy implementation of jQuery.

2. Cross-Browser Compatibility:

One of the characteristic benefits of using jQuery is the fact that it deals with many cross-browser issues and bugs that we would experience while developing using JavaScript only. Handling a cross-browser web development problem can be quite a harrowing experience. This is because website design elements might work perfectly in one browser version and completely break down in another. With the jQuery library, most of these cross-browser issues have been dealt with. This means that we can develop a website that will work properly on all types of browsers and different versions, saving us from lots of headaches.

3. Clean And Beautiful Syntax:

jQuery makes use of powerful, clean, and simple syntax that makes it easier to pick the DOM elements on the webpage that we want to change with JavaScript and enable us to chain effects and actions together for effective code. It is common to replace dozens or more JavaScript lines with one line of jQuery code. jQuery makes use of Cascading Style Sheets(CSS) version 3 for selecting elements and this means that we do not have to learn a new syntax when using this language.

4. Lightweight And Lean:

To keep the jQuery library lean and lightweight, most functions have been omitted and others have been moved to the plug-in section. If we require any of these omitted features, we can easily add them to our website as plugins. The lean library keeps the coding at a restricted level and helps save on bandwidth to guarantee faster loading. The core jQuery library is just 24 kb, which is smaller than a photograph on most websites, and browser applications will only download and cache it once for use on all our webpages. The best Web design company New York has will use jQuery because of its many benefits.

5. Open Source Library:

jQuery is an open-source library that is free and supported well across different applications. This means that anyone can use this language in their applications without worrying about any licensing or compatibility issues. Furthermore, jQuery has been officially integrated into the IDE Visual Studio 2010 by Microsoft. Additionally, JQuery intelligence is now supported well in the Visual Studio 2010.

6. Animations And Cool Effects:

Flash developers are quite costly and developing in Flash needs lots of experience and may take years of practice for one to come up with movie-like creations that make flash popular. Conversely, jQuery is free and only necessitates knowledge of HTML and JavaScript. JQuery utilizes a combination of CSS, AJAX, JavaScript, and HTML. These markup-based technologies have been designed to work perfectly together. As a result, we can use an optimization strategy on our website without necessarily making special adjustments that technologies like Flash require. With jQuery, we can create great-looking effects and animations that will keep our target audience engaged.

7. Highly Extensible:

The primary jQuery library is designed to be focused and kept tight, eliminating any non-essential features. However, a plugin framework is provided, making it easy to extend jQuery and this includes both official jQuery plugins and thousands of third-party plugins. This means that our page will only download the specific features that it requires. In case we need other features that are not included in the main library, then we can easily get superior quality downloads online.

8. Pages Load Faster:

Search engines like Google use page load time as a key factor when ranking websites.  As a result, every web developer must strive to ensure that their code is concise and light as possible. jQuery files are usually stored separately from the webpage itself. This allows developers to make modifications to the entire website using one central repository rather than search through numerous folder structures.

9. SEO-Friendly:

The way that a developer codes a website can greatly affect the way it can be found on the search engines. jQuery can easily be optimized for the search engines and has lots of plug-ins that can help developers achieve this. One of the SEO-friendly practices that we can use is embedding jQuery elements using unordered lists.  

10. Utility Features:

JQuery provides utility functions that aid in coding string iteration, trimming, array manipulation, and many more features. These functions provide a seamless integration between JavaScript and jQuery. With these essential utility features, the code writing process will be hassle-free and easier.

It is important for website developers to learn jQuery because it is worth the effort, time, and money and is also a key component of HTML5. This library can offer stunning effects on our website, which will surely bring success. With little coding and more HTML5 integration, jQuery will be a big part of web development in the near future. jQuery has all the tools we need to build a website or web app that is interactive and highly engaging.

Fundamentals of jQuery:

Introduction to jQuery, Why jQuery, Advantages of jQuery, JQuery fundamentals, Installation Process of jQuery, jQuery Syntax, jQuery Selectors, jQuery Events, jQuery Syntax For Event Methods, Commonly Used jQuery Event Methods, The on() method in jQuery,  Page layout using jQuery

Installing jQuery:

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

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

Introduction to jQuery, Why jQuery, Advantages of jQuery, JQuery fundamentals, Installation Process of jQuery, jQuery Syntax, jQuery Selectors, jQuery Events, jQuery Syntax For Event Methods, Commonly Used jQuery Event Methods, The on() method in jQuery,  Page layout using jQuery

1. 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 we 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 we choose what to download, click the download button. We 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 our website (and pages) are located.

2. Using a CDN:

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

For example, Google has jQuery on their CDN. Because jQuery updated 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 we use.

Installation Process of 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 we download jQuery, change the src to a filename. Example:
<script src= “jquery-1.8.0.min.js”></script>”>

All these <script> elements should be put inside the <head> of our 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.

jQuery 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.

Introduction to jQuery, Why jQuery, Advantages of jQuery, JQuery fundamentals, Installation Process of jQuery, jQuery Syntax, jQuery Selectors, jQuery Events, jQuery Syntax For Event Methods, Commonly Used jQuery Event Methods, The on() method in jQuery,  Page layout using jQuery

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.
Introduction to jQuery, Why jQuery, Advantages of jQuery, JQuery fundamentals, Installation Process of jQuery, jQuery Syntax, jQuery Selectors, jQuery Events, jQuery Syntax For Event Methods, Commonly Used jQuery Event Methods, The on() method in jQuery,  Page layout using jQuery

The dollar sign($) is the function to select something. It is similar to:
function $ (id) {
return document.getElementById(id);
}

From the code line shown in the image, we have:

1. window: The window is the selected object. This means that jQuery is selecting the entire window.

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

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

4. 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.

5. }); 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.

jQuery 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.

Introduction to jQuery, Why jQuery, Advantages of jQuery, JQuery fundamentals, Installation Process of jQuery, jQuery Syntax, jQuery Selectors, jQuery Events, jQuery Syntax For Event Methods, Commonly Used jQuery Event Methods, The on() method in jQuery,  Page layout using jQuery

1. 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 we like we 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.  

2. 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.  

3. 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.

4. 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 we find that the selectors don't work when we try them, and we are sure that they are correct and they should work, we 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 of 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.

jQuery Events:

All the different visitors' actions that a web page can respond to are called events. An event represents a precise moment when something happens.

Introduction to jQuery, Why jQuery, Advantages of jQuery, JQuery fundamentals, Installation Process of jQuery, jQuery Syntax, jQuery Selectors, jQuery Events, jQuery Syntax For Event Methods, Commonly Used jQuery Event Methods, The on() method in jQuery,  Page layout using jQuery

Examples:
1. moving a mouse over an element
2. selecting a radio button
3. clicking on an element

The term "fires/fired" is often used with events. Example: "The keypress event is fired, the moment we press a key".

Here are some common DOM events:
Mouse Events
Keyboard Events
Form Events
Document/Window Events
click
keypress
submit
load
dblclick
keydown
change
resize
mouseenter
keyup
focus
scroll
mouseleave

blur
unload

jQuery Syntax For Event Methods:

In jQuery, most DOM events have an equivalent jQuery method. To assign a click event to all paragraphs on a page, we can do this:
$("p").click();

The next step is to define what should happen when the event fires. We must pass a function to the event:
$("p").click(function(){
 // action goes here!!
});

Commonly Used jQuery Event Methods:

1. $(document).ready():

The $(document).ready() method allows us to execute a function when the document is fully loaded.

2. click():

The click() method attaches an event handler function to an HTML element. The function is executed when the user clicks on the HTML element. The following example says: When a click event fires on a <p> element; hide the current <p> element:
Example:
$("p").click(function(){
  $(this).hide();
});

3. dblclick():

The dblclick() method attaches an event handler function to an HTML element. The function is executed when the user double-clicks on the HTML element:

Example:
$("p").dblclick(function(){
  $(this).hide();
});

4. mouseenter():

The mouseenter() method attaches an event handler function to an HTML element. The function is executed when the mouse pointer enters the HTML element:

Example:
$("#p1").mouseenter(function(){
  alert("You entered p1!");
});

5. mouseleave():

The mouseleave() method attaches an event handler function to an HTML element. The function is executed when the mouse pointer leaves the HTML element:

Example:
$("#p1").mouseleave(function(){
  alert("Bye! You now leave p1!");
});

6. mousedown():

The mousedown() method attaches an event handler function to an HTML element. The function is executed, when the left, middle or right mouse button is pressed down, while the mouse is over the HTML element:

Example:
$("#p1").mousedown(function(){
  alert("Mouse down over p1!");
});

7. mouseup():

The mouseup() method attaches an event handler function to an HTML element. The function is executed, when the left, middle or right mouse button is released, while the mouse is over the HTML element:

Example:
$("#p1").mouseup(function(){
  alert("Mouse up over p1!");
});

8. hover():

The hover() method takes two functions and is a combination of the mouseenter() and mouseleave() methods. The first function is executed when the mouse enters the HTML element, and the second function is executed when the mouse leaves the HTML element:

Example:
$("#p1").hover(function(){
  alert("You entered p1!");
},
function(){
  alert("Bye! You now leave p1!");
});

9. focus():

The focus() method attaches an event handler function to an HTML form field. The function is executed when the form field gets focus:

Example:
$("input").focus(function(){
  $(this).css("background-color", "#cccccc");
});

10. blur():

The blur() method attaches an event handler function to an HTML form field. The function is executed when the form field loses focus:

Example:
$("input").blur(function(){
  $(this).css("background-color", "#ffffff");
});

The on() Method:

The on() method attaches one or more event handlers for the selected elements. Attach a click event to a <p> element:

Example:
$("p").on("click", function(){
  $(this).hide();
});

Attach multiple event handlers to a <p> element:

Example:
$("p").on({
  mouseenter: function(){
    $(this).css("background-color", "lightgray");
  },
  mouseleave: function(){
    $(this).css("background-color", "lightblue");
  },
  click: function(){
    $(this).css("background-color", "yellow");
  }
});

Page Layout Using jQuery:

Create advanced UI layouts with sizable, collapsible, nested panels and tons of options. The layout can create any UI look we want; from simple headers or sidebars to a complex application with toolbars, menus, help-panels, status bars, sub-forms, etc. Integrates with and enhances other UI widgets, like tabs, accordions, and dialogs, to create rich interfaces.

We can directly download the page layout and apply in our code. Demo page layout using jQuery is shown below:
<!DOCTYPE html>
<html>
<head>
      <title>Basic Layout Example</title>

      <script type="text/javascript" src="js/jquery.js"></script>
      <script type="text/javascript" src="../source/stable/jquery.layout.js"></script>

      <script type="text/javascript">
      $(document).ready(function(){
            $("body").layout({ applyDemoStyles: true });
      });
      </script>

</head>
<body>

<div class="ui-layout-center">Center</div>
<div class="ui-layout-north">North</div>
<div class="ui-layout-south">South</div>
<div class="ui-layout-east">East</div>
<div class="ui-layout-west">West</div>

</body>
</html>

Introduction to jQuery, Why jQuery, Advantages of jQuery, JQuery fundamentals, Installation Process of jQuery, jQuery Syntax, jQuery Selectors, jQuery Events, jQuery Syntax For Event Methods, Commonly Used jQuery Event Methods, The on() method in jQuery,  Page layout using jQuery

No comments:

Post a Comment

If you have any doubt, then don't hesitate to drop comments.