×
Community Blog An Introduction to jQuery

An Introduction to jQuery

This article explores how jQuery can help with building highly responsive websites without adding any unnecessary complexity in the process.

By Alex, Alibaba Cloud Community Blog author.

Often referred to as a lightweight, write-less-do-more JavaScript library, jQuery makes the development of HTML programs easier. jQuery's core objective is to make the use of JavaScript for website development painless. jQuery eliminates repetitive tasks while tackling problems with JavaScript through methods called by a single line of code. The increasing sophistication of browser technologies and requirements for client logic makes working with JavaScript and HTML quite challenging. However, as one of the leading JS libraries, jQuery makes normalization of features and their implementation easier.

One of the advantages of using jQuery is the significant increase in productivity without much difficulty to either learn or work with the library. Using jQuery greatly improves a JavaScript developer's skills for tackling UI requirements and front-end logical problems. This article introduces jQuery's core concepts related to the areas around client-side development.

Basic knowledge of HTML, CSS or JavaScript is essential to understand this article better.

jQuery Features

Before we deep dive into the application of jQuery in practical scenarios, let's take a look at some of its key features:

DOM Element Selectors

jQuery incorporates the Document Object Model (DOM) Element Selectors to make DOM element selection possible using its operational methods. Get single or multiple elements in a document using their ID, CSS class, and attribute filters or their relationships, respectively.

The jQuery Object (The Wrapped Set)

The Wrapped set is a jQuery object resulting from the DOM Element Selectors. Its structure is similar to an array, which enables access to the elements via the indexer. jQuery functions are easily applicable over the wrapped set.

Wrapped Set Operations

Wrapped set operations in jQuery enables the application of all its operations in the wrapped set. The jQuery.fn object allows using more than 100 functions for operations on matched sets as well as manipulation in case of DOM objects selection. It also facilitates access to other operations such as styles, cloning elements or creating new ones among others. Also, wrapped set operations support a more powerful operation in a single command that delivers a result from the jQuery wrapped set object. Overall, it's a good choice of functionality from a relatively small API to learn.

Event Handling By jQuery

Different browsers have divergent requirements for DOM implementation. However, JavaScript handles asynchronous events such as AJAX calls and DOM manipulation, which poses a challenge while dealing with various browsers. jQuery provides a standard way of handling event models across supported browsers.

jQuery Footprint

jQuery is full of features in a rather compact library and offers access to numerous functionalities at just 16 KB.

Easy Plug-in API

jQuery provides an easy-to-use plugin API that allows incorporating hundreds of new plugins to perform a variety of DOM operations. In addition, it provides an extensive library of features.

Getting Started With jQuery

There are two methods to begin with jQuery:

  • Download the library from jQuery.com
  • Import jQuery through a content delivery network (CDN) such as Google or Microsoft

The jQuery website provides both a production and development version of the tool's library for download. Refer to the single JavaScript file using an HTML <script> tag in the head section as shown below.

<head>
<script src="jquery-3.3.1.min.js"></script>
</head> 

Alternatively, import the library from a jQuery CDN. With a Google API, implement it as shown below.

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

Similarly, run the code below for the Microsoft CDN.

<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
</head> 

It is beneficial to use the CDN method since most users already download the library while accessing other websites. As a result, it caches previously and thus, loads automatically when users visit their website, leading to better response times. Response times improve further as CDNs serve requests from the servers closest to a user resulting in more optimization.

jQuery Syntax

As mentioned in the preceding section, jQuery allows querying HTML elements and also manipulates them. The syntax allows the selection of HTML elements as well as their manipulation through a variety of supported operations.

A jQuery syntax: $(selector).action()

where:

  • $: Defines or accesses jQuery
  • (selector): Query for HTML elements
  • action(): Defines the operations to be performed on DOM elements

Below are some of the popular syntaxes on jQuery:

  • $(this).hide() ¨C Hides the DOM element currently being handled
  • $("p").hide() ¨C Hides all described elements
  • $(".test").hide() ¨C Hides all elements of described class
  • $("#test").hide() ¨C Hides the element with described id

jQuery Selectors

A jQuery selector directs the elements to be handled. There's much familiarity with CSS albeit some elements only specific to jQuery. The following snippet shows the structure of jQuery selectors.

$("selector")

Following is the list of some of the most commonly used jQuery selectors:

  • $("*") - Wildcard: Selects all the elements on a page.
  • $(this) - Current: Selects a single element being within a function.
  • $("p") - Tag: Selects all instances in a

    tag.

  • $(".example") - Class: Selects all elements associated with the example class.
  • $("#example") - Id: Selects only one instance with the example id.
  • $("[type='text']") - Attribute: Selects all elements that have text applied to the attribute type.
  • $("p:first-of-type") - Pseudo Element: Selects the first element from

    .

Usually, most practical applications deal with classes and ids.

jQuery Effects

jQuery effects helps to couple the events with various operations that enable the manipulation of elements on the webpage, such as adding animations. Let's take a look at how to implement a popup overlay using a practical example.

For simplicity, let's consider a single class to open and close the overlay with only one function instead of two, unlike the case of using two different IDs. Consider a hypothetical HTML file shown below.

index.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery Effects</title>
  <style>
  div {
    background-color: red;
    width: 80px;
    border: 1px yellow;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
<button id="go">&raquo; Run</button>
<div id="block">Animation!</div>
 
<script>
// Using multiple unit types within one animation.
 
$( "#go" ).click(function() {
  $( "#block" ).animate({
    width: "60%",
    opacity: 0.4,
    marginLeft: "1in",
    fontSize: "2em",
    borderWidth: "10px"
  }, 1500 );
});
</script>
 
</body>
</html>

The jQuery .animate() is very useful for creating animation effects. It is applicable to all the CSS property objects. The .css() method requires defining a plain object albeit with some limited functions. Changing the property value of the CSS alters an element from one state to another. It does not however animate string value such as background color, only numerical values such as width: "60%", opacity: 0.4 or the "show", "hide" and "toggle" strings.

Below are some of the most common methods:

- toggle() 
- show()
- hide() 
- fadeToggle()
- fadeIn()
- fadeOut()
- slideToggle() 
- slideDown()
- slideUp()
- animate()

Overly, jQuery effects mostly constitute one of the following:

- jQuery Hide/Show
- jQuery Fade 
- jQuery Slide 
- jQuery Animate 
- jQuery stop() 
- jQuery Callback 
- jQuery Chaining

With the jQuery effects, element manipulation occurs once a user takes an action that affects an element on the webpage.

jQuery Events

The jQuery events describe all the actions of a user on a webpage, usually actions that the page responds to. Some examples include:

  • Mouse cursor movement over elements
  • Selecting radio buttons
  • Clicking on elements

There are certain methods that are associated with jQuery events. Below are some of these examples.

click()

This method attaches an event handler function to an element in HTML when a user clicks on an element on the webpage. In the example below, the current

element will be hidden from view.

$("p").click(function(){
    $(this).hide();
});

dblclick()

This method attaches an event handler function to an element in HTML when a user double clicks on an element on the webpage. In the example below, the current

element will be hidden from view.

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

mouseenter()

This method attaches an event handler function to an element in HTML when a user moves the mouse cursor to the center of an element on the webpage. Refer to an example below:

See an example below:

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

mouseleave()

This method attaches an event handler function to an element in HTML when a user moves the mouse cursor away from an element on the webpage.

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

Further, there is a possibility of chaining more than one event handlers using the on() method. Consider the example below:

$("p").on({
    mouseup: function(){
        $(this).css("background-color", "orange");
    }, 
    mousedown: function(){
        $(this).css("background-color", "green");
    }, 
    click: function(){
        $(this).css("background-color", "red");
    } 
});

Conclusion

This article explores how to select and manipulate elements using jQuery. It illustrates how events and effects coupled together lead to powerful user experience. In a nutshell, this tutorial serves to inform just how the jQuery syntax and methods allow for ease of handling HTML elements in response to user input. With simple methods for loading data behind the scenes, the jQuery library helps in building highly responsive websites without any complexity.

Don't have an Alibaba Cloud account? Sign up for an account and try over 40 products for free worth up to $1200. Get Started with Alibaba Cloud to learn more.

0 0 0
Share on

Alex

42 posts | 4 followers

You may also like

Comments

Alex

42 posts | 4 followers

Related Products