Introduction to jQuery and Integrating with Bootstrap
jQuery refers to a lightweight and concise JavaScript (US) library that aims to make JS programming easier and swifter. It is a feature-rich and open-source library that simplifies several complicated tasks such as manipulating and traversing an HTML/CSS page, handling events, animating objects, and making Asynchronous JavaScript and XML (AJAX) calls.
The library offers an easy-to-use Application Programming Interface (API) that is compatible across several browsers. It wraps several common tasks into built-in methods. A Web developer can invoke the desired method by writing just a single line of JS code instead of writing several lines of it. This is how jQuery accomplishes the purpose of ‘get more by writing less’.
Benefits of Using jQuery over JS
There are many JS frameworks available but jQuery is perhaps the most extendable one. Big brands such as Google, IBM, and Microsoft are using it.
- Unobtrusive JS: jQuery helps in designing Webpages through unobtrusive JS, an approach that separates functionality between the presentation and structure of a Webpage. In other words, inserting an event code in the script tag keeps the behavior separate from the Webpage’s structure or content.
- Ease of Use: This is due to the simple yet robust syntax and significantly reduced lines of JS code.
- Big and Focused Library: Unlike other JS libraries, Web developers can perform a variety of functions. Further, to make JS tasks easier, jQuery offers several utility functions. With these functions, Web developers can parse data, trim strings, and search for array elements based on a filter. However, the library is focused, which means it contains only essential features. A Webpage downloads only those features that it requires.
- Extensibility: jQuery comes with a plugin framework due to which it is simple to extend jQuery.
The framework includes both third-party and official plugins. So, if a feature does not exist in the library, a Web developer may include it through a plugin. - Browser Compatibility: Just as in few other IS libraries, jQuery flawlessly resolves cross-browser issues. JS implementations tend to vary amongst browsers, which can take much time of Web developers to get the code working across browsers. However, the makers of jQuery have already implemented the code to display Webpages seamlessly across all major browsers.
- Strong Community: Although a new library, jQuery has an exclusive community through which the dedicated developers tend to improve its functionality. Through this community, there are several plugins available to accelerate the Web development process. Most of the plugins are secured and efficient.
- AJAX Support: jQuery easily allows creating AJAX templates for gaining the benefits of smoother interfaces and efficient loading. A user can perform an action on a Webpage without reloading the whole page.
- Comprehensive Documentation: Official Website of jQuery has in-depth documentation and tutorials, which helps even a beginner in programming to start easily.
Using Bootstrap and jQuery Together
The theme allows using Bootstrap-themed widgets without breaking the appearance of components. Originally, Bootstrap and jQuery cannot exist simultaneously due to which using them together triggers conflicts with JS and CSS styles and classes. However, the new theme comes with the relevant JS and CSS for designing a Web application using jQuery and Bootstrap. It also offers the Bootstrap theme for several third-party jQuery widgets for designing user interfaces. Following are the steps to use the theme:
- Download the archive from the Internet.
- Unzip it.
- Look for custom-theme folder within the css folder of the unzipped package.
- Move the custom-theme folder to the css folder of the Web application for which this theme is to be used.
- Add the relevant css files to the Website’s layout.
Using jQuery in Web Applications
The jQuery library is a JS file that a Web developer uses for programming in jQuery for developing a Web application. There are two ways to use the file, which are as follows:
- Download the library file from jQuery.com and refer it in the HTML code just as a Web developer would do for any other IS file. Save the downloaded file in the directory of Webpages.
- Include the library into the code by referring to a CDN, such as Google and Microsoft. Code Snippet 1 shows how to refer to the Microsoft CDN.
Code Snippet 1:
<head>
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>
</head>
Understanding the jQuery Syntax
With Query, a Web developer can quickly find and select an HTML element and trigger the desired action or actions on it. For this purpose, the makers of Query have offered a customized syntax, which is as follows:
$ (selector) . action ()
where,
- $: Is the sign that indicates the use of jQuery and is the jQuery identifier.
- (selector): Is used to find and select the HTML element or elements.
- action (): Is an action that jQuery should perform on the selected element or elements.
Following are a few samples that indicate how the syntax is used: - $ (this). hide () for hiding the element that is selected at present
- $ (“div”). fade In () for fading in all < div› elements
- $ (“#info”). hide () for hiding an element whose id is set as info
- $ (“.info”). show () for showing an element whose class attribute as the value, info
From these examples, it is clear that the selector can be an id, class, element, or this. Any jQuery code exists within the document ready event. This helps in executing the code only after the Document Object Model (DOM) loads completely or is ready.
Syntax
$ (document) . ready (function ()
{
// Code jQuery functions here.
}) :
OR
$ (function () //Alternate syntax
// Code jQuery functions here.
}) :
Where
- $: Is the jQuery identifier.
- document: Refers to the DOM of the HTML page.
- ready: Is an event that is raised when the fully loaded DOM is ready for manipulation through JavaScript. At this point, the script can safely find and access the HTML elements in the DOM. For example, it can find the <a>element for associating it with a click event handler.
- function: Refers to an anonymous function, as it has no name and it contains an action to be taken.
It is rational to wait for the DOM to load fully before the HTML page handles any requests and responses. This is because it is not sensible to hide an element or resize an image, which is not loaded completely. This enables a Web developer to include JavaScript code inside the tag.
Function in jQuery
In jQuery, a Web developer can define a function in four different ways. It is also possible to define a custom function.
Basic Declaration
This is the easiest way of declaring a function in jQuery. Code Snippet 2 shows the basic declaration to define a function in jQuery.
Code Snippet 2:
function Multiply(var1, var2, var3)
{
return (var1* var2 * var3) ;
}
document write (“Basic Way:”+Multiply (10, 10, 8)) ;
In Code Snippet 2, the Multiply function is defined to return the product of three numbers. This way of declaring a function is useful for testing something quickly. It is not a good choice for supporting code reuse.
Declaration as a Variable Name
A Web developer can define a function through an expression, which is assigned to a variable. After storing the expression in a variable, this variable is then used as a function. Code Snippet 3 uses a variable as a function.
Code Snippet 3:
var Multiply = function (var1, var2, var3)
{
return (var1 * var2 * var3)
}
document write(“Function as Variable Name “+Multiply (10, 10, 8)) :
In Code Snippet 3, the code declares the variable Multiply and assigns an anonymous function to it. This function returns the product of three numbers. In the write () method, the variable itself is used as a function to return the product.
Self-invoking Function Declaration
Apart from assigning an anonymous function to a variable, a Web developer can pass it directly to a method. This argument acts as a self-invoking function, which is typically an expression that the script automatically invokes without being called. It has no name and is impossible to call it explicitly.
To declare such a function expression, a Web developer should add parentheses around the function. Code Snippet 4 defines a self-invoking function.
Code Snippet 4:
(function () {document write (“Self Invoking Function, Hello! I called myself”) :}) () :
In Code Snippet 4, the self-invoking function is within parentheses and calls itself on its own. The string is the output that is displayed in the browser.
User-defined Function Declaration
Web developers can create their own jQuery functions, which are known as user-defined functions.
The jQuery. fn or $. fn object allows creating a user-defined function. It is equal to jQuery prototype. Code Snippet 5 creates a user-defined function.
Code Snippet 5:
$ (document) . ready (function () {
$.fn. myFunction = function () {
alert (‘You have successfully defined the function!’);
}
$ (“•call-btn”) •click (function () f
$. fn. myFunction () ;
}) ;
}) ;
In Code Snippet 5, $ . fn object allows creating a user-defined function, my Function, which shows an alert message. It makes the function available for all objects of Query. This is evident when the click property of the button whose class attribute is set to call-btn which is used to invoke the newly created function.
Selectors in jQuery
The jQuery library allows using CSS and its own custom selectors for swiftly accessing and manipulating the HTML elements in the DOM. A jQuery Selector refers to a function in the form of an expression for searching the matching element in the DOM. In other words, selectors allow selecting single or multiple HTML elements for triggering different actions on the selected ones. All selectors begin with the jQuery identifier ($), which is followed by parentheses. The library allows accessing the elements by:
- ID
- Class name
- Tag name
- Attribute
- Attribute values
- Other selectors
ID Selector
ID selector refers to the id attribute of a tag for searching the corresponding element. As the ID of each element is unique, the selector is useful only for finding a single tag at a time. It works by relying on the document. getElementById () function.
To find a tag or an element through its ID, a Web developer needs to specify ID selector, by beginning it with the hash (#) character and following it by the id value of the element.
Syntax
$ (‘#<id>’)
where,
id: Is the value of id attribute of the required HTML element.
Following are some points to remember about ID selector:
- It is the most efficient of all selectors.
- It accesses only the first element, in case of two or more tags with the same ID.
- It is not the same as document. getElementById (), as the latter returns a DOM object and the former returns a jQuery object that includes the DOM object and provides different methods. Therefore, a Web developer can invoke jQuery methods such as click () on the returned object. To refer to the underlying DOM object using a jQuery object, a Web developer should use, $ (‘#btnidentifier’) [0].
- It is slower in execution than document. getElementById(). Still, it is in use for harnessing the power of the extra functionality or methods of a jQuery object.
The Class Selector
The class selector looks for HTML elements that have the specified class. It works by using the getElementsByClassName () native function. However, the user’s browser should support this function. To find a tag or an element through its class, a Web developer needs to specify the class selector by beginning it with the dot (.) character and following it by the class name of the element.
Syntax
$ (‘.<class>’)
where,
class: Is the value of class attribute of the required HTML element.
Code Snippet 6 shows some examples of class selectors.
Code Snippet 6:
$(‘small’) // Selects all elements with class small
$(‘ small, big’) // Selects all elements with class small or big
The Element Selector
The element selector access elements as per their name. To find an element by its name, a Web developer needs to specify the element selector within the parentheses following the $ character.
Syntax
$(<element>)
where,
element: Is the name of the element.
Code Snippet 7 shows some examples of element selectors.
Code Snippet 7:
$(‘td’) // Selects all elements
$ (‘div a’) // Selects all anchor elements that are inside the div element
The Checked Selector
The checked selector accesses and selects all selected radio buttons and check boxes. To access these input controls, a Web developer needs to include: checked inside double quotes, which should be within the parentheses following the $ character.
Syntax
$ (“‘: checked”)
Code Snippet 8 shows how to access all radio buttons at once that a user has selected.
Code Snippet 8:
$ (‘ input [type=”radio”]: checked’ )
JSON and Conversions to JSON
JSON refers to a lightweight format for exchanging and storing data. It is an easier alternative to Extensible Markup Language (XML) in terms of usage. This is because it is a self-describing format due to which it is simple to comprehend the data exchanged between a server and a client (browser).
Exchanging data between these two nodes happens only in text format. JSON is a simple text format to use in this scenario, although it uses JS syntax. It also works independent of any programming language.
A Web developer can convert an object into JSON and then send it to the server. It is also possible to convert data obtained from the server into ISON objects and arrays. Both the processes are free from complex parsing.
Creating a JSON Object
The format of JSON is almost similar to JS objects. So, it is written in the form of key/value or name/value pairs. However, unlike in 5, the key or name in ISON is always a string due to which it must be within double quotes. Further, in IS, strings can appear in single or double quotes.
In JSON, a name in double quotes is separated by the value with a colon.
Syntax
( “name”: value}
In a name/value pair, the value needs to a Valid data type, which can be number, string, boolean, array, null, or object. ISON do not sipet sae data type. So, the only way to represent a date in ISON is to make it a string. Code Snippet 9 shows some examples of name/value pairs in 150N.
Code Snippet 9:
{ “city”: “Karachi”}
{“age”: 25}
(“marriage”: “1999-12-23”}
After identifying the total count along with the check box names, ID selector is used to display the result by invoking its html () method. ID selector is referring to the < div> tag with the id, divResult. This whole process of finding the total count and check box names is triggered as soon as a user clicks the submit button.
Code Snippet 9, city is the key or name in double quotes and Moscow is its string value.
Similarly, age is the key, while 40 is its numeric value. For the marriage key, the value is a string showing the wedding date. In Query, Web developers usually work with JSON objects. Code Snippet 10 shows how to store employee data in a JSON object, employeeJSON.
Code Snippet 10:
var employeeJSON =
{
“firstName”: “Saad”,
“lastName” : “Rizwan”,
“gender”: “Male”,
“salary”: 5000,
“bike”: null
} ;
In Code Snippet 10, the employee data is included inside the curly braces. Further, comma separates each name/value pair. There is no comma at the end of the last name/value pair.
Each name/value pair is referred to as a property. A Web developer can specify any number of properties in a JSON object. Code Snippet 11 represents the same data using XML.
Code Snippet 11:
<Employee>
<FirstName>Saad</Firstname>
<Lastname>Rizwan</Lastname>
<gender>Male</gender>
< salary>5000</salary>
<bike>null</bike>
<Employee>
From Code Snippet 11, it is clear that the JSON format is simpler than XML.
Accessing Data from a JSON Object
The dot (.) notation and the corresponding property name enable accessing data from a JSON object.
Syntax
<Object>. <propertyName>;
Code Snippet 12 shows how to fetch the first name of the employee from the employeeJSON object created in Code Snippet 10.
Code Snippet 12:
var firstName = employeeJSON. firstName;
Using JSON Arrays
Let’s imagine a scenario wherein a Web developer needs to store the data of more than one employee in a JSON object. This is where a JSON array is useful. A JSON array can hold several objects. To create a JSON array, include the objects in square brackets and separate each by a comma. Code Snippet 13 shows how to create a JSON array indicating the colors in a rainbow.
Code Snippet 13:
{ “Red”, “Blue”, “Green”, “Yellow”, “Violet”, “Indigo”, “Orange” }
A JSON array is almost similar to a JS array. However, its values or elements can be number, string, boolean, array, null, or object. It cannot be a valid expression, unlike in JS. Code Snippet 14 shows how to create a JSON object holding the data of two employees.
Code Snippet 14:
var employeesJSON = [
{
“firstName”: “Philips”,
“lastName” : “LG”,
“gender”: “Male”,
“salary”: 5000
},
{
“firstName”: “Samsung”,
“lastName”: “Sam”,
“gender”: “Female”,
“salary”: 4000
}]
In Code Snippet 14, both elements in the array are employee objects. To access these from the JSON array, employeeJSON; a Web developer should use the object’s index position. Code Snippet 15 shows how to retrieve the last name from both the objects of employees JSON array.
Code Snippet 15:
var result = employeesJSON [0]. lastName;
var result = employeesJSON [1]. lastName;
Converting an Object or Array into a JSON String
When sending data to a server, it should be in the string format. So, for converting a JS object into a string, a Web developer should use JSON. stringify (). This method is used on both arrays and objects.
JSON. stringify () takes the array as an input and converts it into a string in SON notation. This string is stored in JSONString variable and is displayed on the Webpage through the < div> tag. This string is now ready to be sent to the server.
Converting a String into a ISON Object or Array
A Web developer can parse a string using JSON. parse () to convert it into a JSON object or an array. To avoid a syntax error, the string should be in JSON format.
Event Delegation in jQuery
jQuery is customized for reacting to events occuring on a Webpage. An event denotes the exact moment when an action from a user occurs. A few examples of events include loading a Webpage, clicking an element, selecting a check box, and hovering the mouse over an element.
With events, Web developers can design dynamic Webpages. When an event is raised, an event listener, which is associated with source of event, listens to it and notifies the handler. An event handler, which is associated with the event, is usually a custom function that conveys what to do for handling the event.
In jQuery, event delegation enables a Web developer to assign a single listener to a parent element, which will listen for all descendants corresponding to a selector.
This is irrespective of whether these descendants are present now or are included later. The descendants of an element encompasses all its children elements including the great grand-child ones.
The on () and delegate () methods facilitate delegating an event in jQuery. Delegating an event eliminates the need to add event listeners to particular tags. This is because a Web developer can now add a listener to a parent element, which can analyze the bubbled events to look for a match on child elements.
For example
let’s assume that there is a parent <ul> element with 50 child elements. Something should happen when a user clicks any child element. For this, a Web developer may add a distinct event listener to each < li> element. However, a problem arises when the developer frequently tends to add and remove these child elements. In this case, adding and removing the listeners would be a tedious job and may lead to performance issues. So, it would be much better to add a listener to the parent element.
However, an important question here is that how would the developer find out which child element was clicked? The solution here is to use the target property of the event object to obtain a reference to the clicked node while the event bubbles up to the parent element.
When the click event triggers on any child element of the<ul> it also triggers on all ancestors of that element. This is called event bubbling in which an event bubbles upwards from the source element in the DOM tree. As a result, it activates each of its parent click handlers, which includes <ul>,<div>,<p>,<body><html>, and root. In other words, clicking an <li> tag indicates clicking the whole body of the document.
Event bubbling and target property are the main features of event delegation in jQuery. They boost performance when there are hundreds of child elements on which a specific event should be listened and handled.
target
The target property of any event refers to the element that originated the event. Through event delegation, a Web developer can add a handler to an element, wait for event bubbling, and quickly identify the event’s source, which is the element where the event occurred. Following are the benefits of event delegation:
- Less handlers to take up memory
- Better performance
- Reduced risk of crashing
- No re-assigning the handlers if the child elements keep changing
1 Comment