JAVASCRIPT AND JQUERY - A SIMPLE START TO JQUERY, JAVASCRIPT, AND HTML5 FOR BEGINNERS (2014

A SIMPLE START TO JQUERY, JAVASCRIPT, AND HTML5 FOR BEGINNERS (2014)

CHAPTER 6: JAVASCRIPT AND JQUERY

You must have got a hang of the power of JavaScript already. In the chapter on JavaScript, you have already learnt how to create and adding JavaScript for making web pages dynamic. The biggest challenge of web development is to design webpage elements that can run just as well on any browser as different browsers provide support for different elements, making it difficult to find a common ground.

This chapter takes you a step further in JavaScript development by teaching you how to create objects and use them. Besides this, it also introduces you to the concept of jQuery, which attempts at creating browser-compatible code. Although, it cannot promise 100% browser compatibility, but it certainly solves the day-to-day issues regarding the same.

How to Create JavaScript Objects

Anything from numbers to strings are objects in JavaScript. Therefore, it is essential to know how to create and deal with these effectively. The simplest way to create objects in JavaScript is using the object literal syntax. The following example illustrates how it is done.

var customer1 = {

yearOfBirth: 2000,

name: 'Alex',

getCustomerInfo: function () {

return 'Customer: ' + this.name + ‘ ‘ + this.yearOfBirth;

}

};

This code creates an object customer1, with the data members, name and yearOfBirth and the member function getCustomerInformation. It is also important to note the use of this keyword, which accesses the values correctly being used or referenced for the object concerned.

Besides this, you can also create objects dynamically using the new keyword. The methods inherited include:

● constructor

● isPrototypeOf

● hasOwnProperty

● toLocalString

● propertyIsEnumerable

● valueOf

● toString

Once the object has been created, properties can be added to the same in the following manner:

function getCustomer(myName, myYearOfBirth) {

var newCust = new Object();

newCust.name = myName;

newCust.yearOfBirth = myYearOfBirth;

newCust.getCustomerInfo = function () {

return 'Customer: ' + this.name + ‘ ‘ + this.yearOfBirth;

};

return newCust;

}

This code creates an object newCust dynamically. Several instances of this can be created in the following manner:

var cust1 = getCustomer (‘Alex’, 1978);

var cust2 = getCustomer (‘David’, 1986);

Although, JavaScript doesn’t support a particular keyword ‘class’, but you can simulate classes using the method mentioned above.

Namespaces

There is no specific keyword like namespace for implementing namespaces. However, namespaces can be implemented using the concepts of classes and objects. If you classify variables and methods into objects and access them as instances of these objects, then you are placing only the names of these objects in the global namespace, reducing the scope of the variables to the object that they belong.

Implementing Inheritance

You can define ‘is-a’ relationships between objects in JavaScript by creating objects and then classifying those objects on the basis of their common characteristics. For instance, if you are implementing an object for employee of a company. You can create objects for specific types of objects like managerTechnical, managerGeneral, technicalStaff, recruitmentStaff and officeStaff and then classify them into objects, technicalStaff, which includes the objects managerTechnical and technicalStaff, and adminStaff, which includes the managerGeneral, recruitmentStaff and officeStaff. In a similar manner, new functions can also be defined.

Working with jQuery

JQuery is a library of browser-compatible helper functions, which you can use in your code to minimize the efforts required for typing, implementation and testing. These functions are essentially written in JavaScript. Therefore, you can also call jQuery, a JavaScript library.

The list of functionalities that are available in jQuery include:

● Attributes, which are a group of methods that can be used for getting and setting attributes of the DOM elements.

● Ajax, which is a group of methods that provide support for synchronous and asynchronous server calls.

● Core Methods are the fundamental jQuery functions.

● Callbacks object is an object provided for management of callbacks.

● Data Methods are methods that facilitate the creation of association between DOM elements and arbitrary data.

● CSS Methods are methods that can be used for getting and setting CSS-related properties.

● Dimensions are methods that can be used for accessing and manipulating the dimensions of DOM elements.

● Deferred object is an object that is capable of registering multiple callbacks while maintaining the data of state change and propagating the same from one callback to the next.

● Forms are methods that are used for controlling form-related controls.

● Traversing, this is a group of methods that provide support for traversing the DOM.

● Effects are methods that can be used for creating animations for your webpage. Events are methods used to perform event-based execution.

● Selectors are methods that can be used for accessing elements of DOM in CSS selectors.

● Offset are methods that are used to position the DOM elements.

● Utilities, which is a group of utility methods

Before getting to use jQuery, you will need to include it into your project. Once you have installed it and you are ready to use it to your project, the next step is to learn how to use it.

First things first, you need to reference the jQuery library on the webpage that needs to use it in the following manner:

<script type="text/javascript" src="Scripts/qunit.js"></script>

<script src="Scripts/jquery-1.8.2.js"></script>

The next thing to know is that the jQuery code that you are hoping to use in your HTML page lies in the jQuery namespace, which has an alias $. Therefore, you can write either jQuery.jFeature or $.jFeature when referring to a feature of jQuery.

Before, you can start using it in your webpages, you will also need to change the default.js file as follows:

function initialize() {

txtInput = $('#txtInput');

txtResult = $('#txtResult');

clear();

}

This allows you to use jQuery and CSS selectors by matching them using their IDs.

Also, as you move ahead with coding using jQuery, remember to refresh the screen using Ctrl+F5 after making any changes as the browser may not be able to catch the JavaScript modification right away. Moreover, use jQuery objects as much as possible because the cross-browser compatibility that they offer.

A DOM object can be referenced from a jQuery wrapper in the following manner:

var domElement = $('#txtInput')[0];

Here is a simple code that checks if the element exists before referencing it.

var domElement;

if($('#txtInput').length > 0){

domElement = $('#txtInput')[0];

}

How to Create a jQuery wrapper for Referencing a DOM element

A jQuery wrapper can be created from a DOM element reference in the following manner:

var myDoc = $(document);

var inText = $(this).text();

The first statement assigns the wrapped object to the variable. On the other hand, the second statement wraps the object referenced using this.

How to Add Event Listeners

jQuery provides the .on method for subscribing to events. Besides this, you can unsubscribe using the .off method. These methods can be used in the following manner:

$('#btnSubmitInfo').on('click', onSubmit);

$('#btnSubmitInfo').off('click', onSubmit);

How to Trigger Event Handlers

JQuery provides triggers or the method, triggerHandler, for triggering event handlers or handler code execution. This can be done in the following manner:

$('#btnSubmitInfo').triggerHandler('click');

Initialization Code

You will often be faced with the requirement to run an initialization code upon the loading of an HTML document. You can do this using jQuery in the following manner:

<script>

$(document).ready(function () {

initializationFunction();

});

</script>

This can be placed at the bottom of the HTML document. It will call the initializationFunction.