AJAX & Web 2.0 Articles

Angular 2 Programming Languages

Programming Languages for Angular Development

Angular 2 differs from Angular JS in regards to programming language support. With Angular JS you generally program in JavaScript. With Angular 2 the official site provides example code in several languages; JavaScript, TypeScript and Dart.

JavaScript is an implementation of the ECMAScript standard. Several versions exist including ES5 and ES6. Most current browsers fully support JavaScript ES5. This means that code compliant with ES5 will run on most most browsers without modification. ES6 on the other hand may not be supported and is typically converted to ES5 before it gets to the browser. The more recent version of JavaScript (ES6) adds features and makes certain tasks easier. It is not clear when browsers will be fully ES6 compliant.

TypeScript and Dart are language super sets of JavaScript. This means they include all the features of JavaScript but add many helpful features as well. But just like the ES6 version of JavaScript they don’t work on current browsers. To work around this limitation there are utilities to convert code written in their non-browser-compliant syntax back to JavaScript ES5. In this way they provide the developer with advanced features and still allow code to be run on existing browsers. The process of converting code from one language to another is referred to as ‘transpilation’. Technically this conversion is performed by a language pre-processor that, although it does not compile anything, is commonly referred to as a compiler.

TypeScript is an open source language that is developed and maintained by Microsoft. It provides type safety, advanced object oriented features, and simplified module loading. Angular 2 itself is built using TypeScript. The documentation support is better on the Angular 2 site for TypeScript than it is for the other options. So although you could write your Angular 2 apps in pure ES5 JavaScript you may find it more difficult and find less support if you get into trouble than if you bite the bullet and spends some time learning TypeScript.

Dart is another alternative for programming Angular 2 applications. It is similar in features to TypeScript and has its own loyal following. If your team is already versed in Dart and is looking to start developing in Angular 2 it could be a good choice. That being said,  in the rest of this post, we will be concentrating on TypeScript.

Code Example

A basic Angular 2 component coded in TypeScript:

import { Component } from '@angular/core';
@Component({
selector: 'hello-app',
template: '<h1>Hello Angular 2</h1>'
})
export class AppComponent { }

 

The same component coded in JavaScript ES5:

(function(app) {
app.AppComponent = ng.core.Component({
selector: 'hello-app',
template: '<h1>Hello Angular 2</h1>'
})
.Class({
constructor: function() {}
});
})(window.app || (window.app = {}));

 As you can see the TypeScript version is more concise and easy to read.

 

TypeScript Usage Basics

TypeScript support is provided by the Node.js ‘typescript’ package. To use typescript you first need to load Node.js and the Node Package Manager (npm). Once Node.js is installed on you system you would use the following command to install TypeScript support:

npm install -g typescript

This will install the TypeScript compiler and allow you to run it from the command line using the following command:

tsc

There are generally three methods to execute tsc. The first method involves passing the name of the TypeScript code file you want compiled on the command line:

tsc filename.ts

Here’s a simple TypeScript code file:

// app.ts
var msg:string = "Hello Typescript!";
function getMessage(message: string){
return message;
}
console.log(getMessage(msg));

Compiling this file produces a JavaScript file with the same name as the TypeScript file but with an extension of “.js”.

tsc app.ts
(produces app.js)

You can test the file by running it using Node.js like this:

node app.js

As your application gets more complex and you have multiple *.ts files in one or more directories you may want to take advantage of the second method of running tsc. To do this you will first need to set up a tsconfig.json config file. Among other things this file tells tsc which directories contain the files you wish to compile. After placing this file in the root of your project tsc will compile any *.ts files it finds whenever they are modified and saved. To use this method you launch tsc in a terminal window and then edit your *.ts files in any text editor. As you save your files they will automatically be converted to JavaScript.

The third method involves using a text editor plugin to determine when you have saved a *.ts file. When that happens the editor itself will call tsc to perform the conversion. This kind of plugin is available for the Atom text editor. Microsoft Visual Studio also includes this type of support. For those who don’t want to load the complete Visual Studio development system Microsoft’s Visual Studio Core text editor also includes TypeScript support.

Conclusion

Using TypeScript significantly simplifies the code you need to write when creating Angular 2 applications. Although TypeScript can’t be executed by browsers directly there are several ways to convert TypeScript into code that browsers can work with.

No Comments

New Support for ECMAScript 2015

Although it is a huge part of the modern web, the syntax of JavaScript hasn’t really changed significantly in quite a long time. That all changed though last June, when ‘ECMAScript 2015’ was released.  This major update contained some significant changes and new features.  Now that more JavaScript engines and environments support the new specification it is a good time to get familiar with these changes.

Besides browsers adding more support for ECMAScript 2015, also call ECMAScript 6 or just “ES 6”, several of the popular JavaScript platforms are adding support as well.  Node.js 4 & 5 support a majority of ES 6, as does AngularJS 2.0.  Of course, like any major version upgrade of such a fundamental web technology, there will be a gradual migration.  We will see a lot of the same things happen with JavaScript that happened with HTML5 and CSS 3, both of which are now “mainstream” and enjoy much broader support.

One thing we’ve learned at Web Age is you can’t wait for “100% support in 100% of environments” to learn about or even begin to adopt a new technology.  It is important to learn about such major upgrades now so that you are aware what is different and look for places where a new version of a technology might be leveraged.

For those looking to keep up with these major changes to JavaScript introduced in ECMAScript 2015, we have a few resources.  The primary one is a new one-day course that focuses on the changes introduced with ECMAScript 2015.  We chose to release a class focused only on the changes since there are lots of people that have JavaScript skills and just need to learn about the changes.  You can find that course here:

WA2488 JavaScript Changes with ECMAScript 2015

We also are going to have a webinar this week that will provide a very quick overview of the changes.  This webinar will cover the main differences with the new ECMAScript 2015 specification and the impact on how JavaScript code can be written.  In particular, focus will be paid on how various ways to leverage the new version while also considering backwards compatibility.  You can register for that webinar here:

WEBINAR: Changes in ECMAScript 2015

As with all new and emerging technologies, we at Web Age look forward to keeping you up to date on what is happening and helping you learn about these technologies to expand the scope of your development skills!

No Comments

Netflix in Flames

Recently I came across this blog post. The title sounded quite intriguing and when reading it, I found some points of interest that I will summarize and present at the end of my blog post.
Read the rest of this entry »

No Comments

Cordova!

This week Apache Cordova (formerly known as PhoneGap) graduated from the Apache incubator and is now a top level Apache project. Cordova got its start as PhoneGap at a company called Nitobi. Adobe acquired Nitobi in 2011 and donated PhoneGap to the Apache Software Foundation which placed in incubator status. Adobe continues to develop PhoneGap as a release of Cordova but indicates that it may acquire some proprietary features.

The Cordova API allows developers to take applications built in HTML5, CSS3 and JavaScript and deploy them natively on a number of mobile platforms. Cordova sits as an abstraction layer on top of the device OS so that by using a different version of Cordova, the same app can run on Blackberry, iOS, Android, Windows Mobile and a host of other mobile platforms. Cordova includes a rendering engine for HTML and CSS as well as a JavaScript runtime. So Cordova applications run ‘natively’ and do not require a web browser.

I first encountered Cordova while working on an Android application for a defense contractor. The application was map focused and allowed users to see where friendly forces (and others if known) were on the battlefield. The application was built natively in Android using Java (Dalvik). A number of potential customers expressed an interest in the application but wanted it on different platforms like iOS or on a desktop browser.We were struggling with the potential of having to rewrite the application for multiple platforms including some proprietary hardware/software used in our industry.

After attending FOSSGEO in Denver, I decided to try a web-based solution using HTML5, CSS3, JavaScript and Sencha’s extJS JavaScript library. At the time, I built the application targeted to the browser. In doing some research I stumbled upon PhoneGap in a matter of hours I was able to demonstrate our application running on Android, iOS and in a desktop browser. As a strategy we were considering porting PhoneGap ourselves to our proprietary platforms and using it as the framework upon which to build a variety of cross platform apps.

In addition to packaging the web functionality, Cordova exposes many native device features including sensors, the file system and contacts. Since Cordova runs as a native app on the device, Cordova-based apps have been accepted in Apple’s iTunes app store. Here is a sampling of Cordova/PhoneGap based apps currently in production:

  • Wikipedia — Wikipedia Mobile
  • Facebook — Mobile SDK
  • SalesForce.com — Mobile Development SDK
  • IBM — Worklight Platform for Mobile
  • Microsoft — Halo Waypoint

As a mobile developer I think Cordova (I still have trouble not calling it PhoneGap) is a credible cross platform solution that can help organizations manage the growing array of mobile platforms in use by their customers and employees.

No Comments

Custom HTML Buttons with CSS

The default <button> and <input type="submit"> tags work great but look super drab. Sometimes, you want jazz things up by adding images and stylized text. This can be easily done by converting a simple <span> into a button replacement.

image

First, we will define a class called "button".

<!DOCTYPE html>
<html>
<head>

<style type="text/css">
.button {
	border-style: outset;
	border-width: 3px;
	padding: 10px 10px 10px 10px;
	border-color: #ECECEC;
	background: #DADADA;
	cursor: default;
}

.button:active {
	border-style: inset;
}
</style>

Note the DOCTYPE declaration. We use the HTML5 syntax which makes a difference in IE. Things may be different if you use an old style DOCTYPE.

The key is to use the :active pseudo CSS selector. This selector matches when an element is clicked on. In normal state, we set the border-style to be outset. When clicked, the style becomes inset. That is the magic.

Then, all we have to do is use the styles from <span> elements.

<p>
Custom HTML buttons: 
<span class="button"><img align="center" src="http://cdn1.iconfinder.com/data/icons/freeapplication/png/24x24/New.png" />
Add Item</span>
<span class="button"><img align="center" src="http://cdn1.iconfinder.com/data/icons/icojoy/shadow/standart/png/24x24/001_39.png" />
Refresh view</span>
</p>

No Comments

Uploading Files Using XMLHttpRequest Level 2

As a part of HTML5, XMLHttpRequest API is undergoing enhancements. You can now upload files to a server and display a progress bar. Files are uploaded in their raw source format. That is not same as uploading a file using the old <input type="file"/> approach.

The basic steps are as follows:

  • Use the HTML5 File API to let the user select a list of files or drag and drop files on an element.
  • Upload these files using XMLHttpRequest Level 2.

Setting Up a Basic UI

Here is a very simple UI for dropping files and uploading them.

<div id="fileDrop">
       <p>Drop files here</p>
</div>
<a id="upload" href="#">Upload files</a>

You can style it better in real life. We will just show the basic code here.

Setting up File Drag and Drop

Within a <script> element, add these lines.

var files;

//Stop default actions
function stopProp(ev) {
    ev.stopPropagation();
    ev.preventDefault();
}

function init() {
    var dropZone = document.getElementById("fileDrop");
    //dropZone.addEventListener("dragenter",  stopProp, false);
    //dropZone.addEventListener("dragleave",  stopProp, false);
    dropZone.addEventListener("dragover",  stopProp, false);
    dropZone.addEventListener("drop",  setFile, false);
	
    var upload = document.getElementById("upload");
    upload.addEventListener("click",  doUpload, false);
}

//Save the dropped files
function setFile(e) {
    e.stopPropagation();
    e.preventDefault();

    files = e.dataTransfer.files;
	
    alert(files[0].name);

    return false;
}

window.onload = init;

function doUpload(e) {
  //Upload code here
}

Basically, when files are dropped, we save them in the files global variable. Also, we set the onclick handler of the Upload link to the doUpload() method.

Upload Files

To keep things simple in this article, we will upload only one of the dropped files. You can easily change the code to upload all files.

Fill out the doUpload() method as follows.

function doUpload(e) {
    var xhr = new XMLHttpRequest();
    var file = files[0];
    xhr.open("POST", "upload.jsp");
    //Set a few headers so we know the file name in the server
    xhr.setRequestHeader("Cache-Control", "no-cache");
    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    xhr.setRequestHeader("X-File-Name", file.name);

    //Initiate upload
    xhr.send(file);

    stopProp(e);
}

The Server Side

The browser sends the contents of the file in the request body. A typical request will look like this.

POST /UploadTest/upload.jsp HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 48
Origin: http://localhost:8266
X-Requested-With: XMLHttpRequest
Cache-Control: no-cache
X-File-Name: Story.txt
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.63 Safari/535.7
Accept: */*
Referer: http://localhost:8266/UploadTest/index.html
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: JSESSIONID=0CDE28BDE75AD2B9486070FDA5AED6DB

Long long ago....

In a galaxy far far away...

If the file is binary, all the bytes will be sent in raw form without any kind of base 64 encoding.

To read this type of data, you will need to get the input stream of the request. In a Servlet or JSP, this can be done by calling ServletInputStream getInputStream() method of HttpServletRequest object. Using the input stream, you can read all the data.

1 Comment

JavaScript Equality Operators

We use equality operators like == and != all the time. They appear to be same as Java or C++ on the surface. But, in reality, things are a lot more complicated and confusing. I will try to explain a few things that may not be obvious.

The Equals Operator (==)

var result = (expr1 == expr2);

When expr1 and expr2 are numbers, a simple number comparison is done. If either of the numbers is a NaN then false is returned.

When expr1 and expr2 are string values, then a string equality is done. If both strings are of equal length and have the same sequence of characters then true is returned.

If one expression is a string and the other a number, then the string is converted to a number before comparison.

var s1 = "10";
var s2 = 10;

var result = (s1 == s2); //result is true

When an object is compared with a number or string, then the system converts the object into number or string prior to comparison.

var s1 = 10;
var s2 = new String("10");

var result = (s1 ==s2);  //result is true

This is same as:

var result = (s1 == Number(s2)); //result is true

When expr1 and expr2 are objects then true is returned if both expressions point to the same exact object. This is where things can get interesting. Consider this example:

var s1 = new String("abc123");
var s2 = new String("abc123");

var result = (s1 == s2); //result is false

Here, result will be false. Variables s1 and s2 are of type object and not string. Since they point to two separate object instances, the equality test fails.

Boolean expressions are converted to number before comparison. There, true converts to 1 and false converts to 0.

var result = (true == 1); //result is true

The null and undefined values are different things in JavaScript. But, they are treated as equals by the operator.

var s1 = null;
var s2; //undefined

var result = (s1 == s2);  //result is true

The Does-not-equals Operator ( != )

This is a reverse of the equals operator. Nothing new to discuss.

The Strict Equals Operator ( === )

This operator tests for type equality in addition to value. If expressions are of different types, then false is returned. It does not do any type conversion like the regular equals operator.

var s1 = "10";
var s2 = 10;

var result = (s1 === s2);  //result is false
result = (s1 == s2); //result is true

Hence, to see if a variable is truly undefined, use the strict test:

var s1 = null;

alert(s1 == undefined); //Wrong! Shows true
alert(s1 === undefined); //Correct. Shows false

The Strict Does-not-equal Operator ( !== )

This is a reverse of the strict equals operator.

No Comments

Coding HTML5 Pages Using Eclipse

The Helios release of the Eclipse IDE for Java EE Developers provides support for HTML5 development. Specifically, it allows you to create HTML5 pages using a new template, provides code completion for HTML5 elements, provides a Properties editor for HTML5 attributes, and provides a WYSIWYG editor for visual development of HTML5 pages.

Creating an HTML5 Page

Before creating an HTML5 page, it’s recommended to set the character encoding type to UTF-8. It defaults to ISO-8859-1. To do so:

1.   Select Window->Preferences from the menu bar.

2.   Expand Web and select HTML Files.

3.   Select ISO 10646/Unicode(UTF-8) from the Encoding drop-down.

clip_image001

4.   Click OK.

Creating an HTML5 page is easy. Simply follow these steps:

1.   Select File->New->Other.

2.   Expand Web and select HTML File. Click Next.

3.   Enter a file name, select the parent folder and click Next.

clip_image002

4.   Select New HTML File (5) for the template and click Finish.

clip_image003

The file will open with the HTML Editor, which provides syntax highlighting (coloring). The tags are displayed in green, the attributes in purple, the attribute values in blue, and the element values in black.

clip_image005

Notice that the document contains the new DOCTYPE element which is used to specify “non-quirks mode” (a.k.a. “standards mode”). It also contains the simplified meta element which is used to specify the UTF-8 character encoding.

Using Code Completion

Using code completion is the same as always. Simply press Ctrl-Space and a list of valid HTML5 elements will be listed.

clip_image001[4]

The same thing applies to attributes. Stick your cursor inside the element’s start tag, press Ctrl-Space, and you’ll see a list of valid attributes:

clip_image003[4]

Using the WYSIWYG Editor

The Helios release of Eclipse also has a WYSIWYG editor for HTML development. It allows you to visually develop your web pages by dragging and dropping widgets from a palette onto your page. Unfortunately, the palette doesn’t include any HTML5 elements at present, but the Properties view was updated to include HTML5 attributes. To make use of the new editor, follow these steps:

1.   Close the HTML file if you already have it open using the HTML Editor.

2.   Right click on the file and choose Open With->Web Page Editor.

The Web Page Editor will open. This is a multi-tab editor. By default, the Design tab is displayed, which offers a split view for easier editing. The top half of the editor displays the visual view of the page and the bottom half of the editor displays the source code. Note that there’s also a Preview tab which displays what the page will look like when rendered by Eclipse’s internal browser.

clip_image005[4]

3.   If you added the canvas element in the last part, go ahead and delete it.

4.   In the right side of the editor, click the left arrow and the Palette will be displayed.

5.   Expand the HTML 4.0 folder to see the list of HTML 4.0 elements. Once again, there are no new HTML5 elements included yet.

clip_image007

6.   Scroll down inside the Palette and drag and drop the Text Field widget onto the page.

Notice that a form element is automatically added to the page. Also, notice that even though you added a text field to the page, the type attribute is not specified. It turns out that in HTML5 the type attribute defaults to “text” if not specified.

clip_image009

7.   Select the text field in the top half of the editor.

8.   Click on the Properties view and its Attributes tab.

9.   Click on the drop-down to the right of autofocus and select autofocus.

clip_image011

10.  Verify that the autofocus attribute is listed in the source code section of the editor. This sets the focus on this field when the form is rendered. Pre-HTML5, you had to do this with JavaScript code.

clip_image013

Note: The editor uses XHTML syntax by default. You don’t need to use XHTML syntax if you don’t want to in HTML5, since HTML is not XML.

11.  Back in the Properties view, scroll down and select required from the drop-down for the required attribute. This means the user has to input a value for this field. Otherwise, he won’t be able to submit the form. Just like with the autofocus attribute, you used to have to do this with JavaScript code.

clip_image015

12.  Likewise, scroll down and verify the type attribute is set to text.

clip_image017

13.  While you’re there, click the drop-down to the right of type. Notice that it reflects the new HTML5 input types, including color, date, datetime, datetime-local, and email.

clip_image019

14.  Your input element should now look as follows:

clip_image021

15.  Drag and drop a Button element on the page to the right of the text field.

16.  Change the value attribute to Submit in the Properties view.

clip_image023

17.  Save the file.

Great! You’ve visually developed an HTML5 page using the Web Page Editor. Note that even if choose not to use this editor and continue using the HTML Editor, the Properties view is still available from there.

Opening the Web Page in a Browser

By default, if you click the browser icon in the Eclipse toolbar, it will open the internal browser, which is based on IE. Unless you’re using Windows 7, the version of IE that’s used is IE7 or IE8, neither of which provide much HTML5 support. Don’t despair. You can change the Eclipse settings to open a different browser, such as Google Chrome 10, Opera 11, or Firefox 4, which provide much better support for HTML5. To do so:

1.   Select Window->Preferences from the menu bar.

2.   Expand General and click Web Browser.

3.   Click New.

4.   Type the name of the browser and specify its location using the Browse button.

clip_image025

5.   Click OK.

6.   Click the Use external web browser button.

7.   Check the box next to the new browser (e.g., Google Chrome).

clip_image027

8.   Click OK.

9.   Click the web browser icon in the toolbar.

clip_image029

The browser should open.

10.  Enter the URL for the page you created.

clip_image031 

Notice the cursor is blinking inside the text field, which means autofocus is working.

11.  Click the Submit button without entering a value in the text field.

clip_image033

Notice an error message is displayed, which means the required attribute is working.

12.  Now input a value and click Submit. This time the form should submit successfully. However, because we didn’t specify a form action, the original page will be displayed, since the form submits to itself.

Making the WYSIWYG Editor Your Default Editor

If you’d like, you can make the Web Page Editor your default editor for HTML files. To do so, follow these steps:

1.   Select Window->Preferences from the menu bar.

2.   Expand General->Editors and select File Associations.

3.   Select .html from the File types list box.

4.   Select the Web Page Editor option in the Associated editors list box.

5.   Click the Default button to the right of it.

6.   Verify the label (default) appears to the right of the Web Page Editor option.

clip_image035

7.   Click OK.

Summary

In this blog posting, we examined how to use Eclipse Helios to create an HTML5 page using the new HTML5 template. We saw that the code completion drop-down was updated to include HTML5 elements. We sampled the new Web Page Editor, which provides us with the ability to develop pages visually. Last but not least, we learned how to change the default web browser used by Eclipse to an HTML5 compliant one.

For more information on HTML5 development, check out our new HTML5 course:

WA1925 Enterprise Web Development using HTML5

30 Comments

So You Want to Write a jQuery Plugin?

If you see yourself repeating the same jQuery code in a couple of pages, it is time to package that into a plugin. In this tutorial we will show you how to get started with jQuery plugin development.

Getting Setup

In your web server’s document root, create a folder called lab. We will create all files here.

In the lab folder, create a simple HTML file called plugin.html. Set the content of the file as follows.

<html>

<head>
<title>jQuery Labs</title>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js">
</script>

<script type="text/javascript">
    $(function(){
    	//jQuery code here
    	
    });
</script>

</head>

<body>
<!-- Body HTML here -->
<p class="c1">Hello World</p>
</body>

</html>

Save the file.

Open a web browser and enter the URL: http://localhost/lab/plugin.html. Make sure that you see the "Hello World" message.

Self Invoking Function

Before we get into plugin development, let’s learn about self invoking functions. This is a JavaScript technique, where a function is called by itself. This is great for functions that initialize things. This eliminates the need for the developers to write extra code to call this function.

Right above the </script> line, add these lines:

(function (msg){
	alert(msg);
}("I got called"));

Save changes. Refresh the browser. You should see the alert dialog.

image

A self invoking function has these syntax elements:

  1. The function may be anonymous or have a name. In the example above, it is anonymous.
  2. The input parameters are supplied within parenthesis right after the end of the function definition (or the last "}").
  3. The whole thing must be wrapped in parenthesis. This is crucial. Without that, you will get a JavaScript compilation error.

Self invoking function has many uses. In the next section, we will see how it plays a role for jQuery plugin development.

Delete the self invoking function before moving to the next section.

Writing a Simple Plugin

Every plugin is a function. This function is added to the prototype of the jQuery object. Recall, how any plugin is called:

$("p1").plugin_func_name(args);

The core function $("p1") returns a jQuery object. Here, plugin_func_name is a property added to the jQuery’s prototype. The value of the property is the plugin function.

Right above the </script> line, add these lines:

(function($){
    $.fn.myPlugin = function() {
        alert("Cool plugin");
    };
}(jQuery));

Here we see a self invoking function. The function is passed the jQuery global object as input. From within the function, we use the symbol $ for the input. Hence, $ is same as the jQuery object. All of this is just to simplify typing (typing $ is easier than jQuery). Using the self invoking function makes sure that the $ sign used here does not conflict with any previously declared variable by the same name ($) by any other toolkit (such as Prototype).

Anyway, the key thing is how we are adding the myPlugin property to the prototype of the jQuery object.

$.fn.myPlugin = function() {
    alert("Cool plugin");
};

Umm… what is this $.fn thing? Shouldn’t it be jQuery.prototype if we are trying to tweak the prototype of the jQuery object? First of all, jQuery and $ are one and the same object. Secondly, the "fn" property is same as the prototype. Somewhere within jQuery code, there is: jQuery.fn = jQuery.prototype. OK, fine. If you want to strictly play by the JavaScript rule, you don’t have to use self invoking functions of $.fn. You could so something like this and things should still work:

jQuery.prototype.myPlugin = function() {
    alert("Cool plugin");
};

But, self invoking function allows you to create private variables and functions. Something you need for complex plugins.

This is perhaps the simplest plugin anyone can develop. Now, we can start using our plugin.

Within the DOM ready handler function, below the line:

//jQuery code here

Add:

$().myPlugin();

Save changes.

Refresh the browser or enter http://localhost/lab/plugin.html. You should see the plugin doing its thing.

image

This is a fully legit plugin. Except it doesn’t do anything that anyone cares about. In the next section, we will change that.

Work on Selected Elements

The core function $() does all the heavy lifting of selecting DOM elements in the page that match the passed selector rule. All a plugin has to do is do something with these elements.

We already know that the each() jQuery function is used to iterate over selected elements. We can use it from our plugin function.

Delete the line:

alert("Cool plugin");

In it’s place, enter the plugin code as shown below.

$.fn.myPlugin = function() {
    this.each(function() {
        this.innerHTML = "Your class is: " + this.className;
    });
};

The "this" keyword within the plugin function points to the jQuery object. Hence, we can call the each() function. Within the iteration handler function, "this" points to the DOM element. Hence, we can use the DOM API and access properties like innerHTML and className.

Change the selector rule from where the plugin function is called.

$(function(){
    //jQuery code here
    $("p").myPlugin();
    	
});

Save changes. Refresh the browser. You will notice that the text of the paragraph changes from "Hello World" to "Your class is: c1".

image

Add another paragraph below the existing one.

<!-- Body HTML here -->
<p class="c1">Hello World</p>
<p class="c2">Hello World</p>

Save changes. Refresh the browser.

image

Review

In this tutorial, we learned the basic structure of writing a jQuery plugin. From this point, you can use the powerful jQuery API to create amazing and cool plugins. For more information on advanced plugin development topics, see this article.

No Comments

The jQuery Object

What does the jQuery core function – $() – actually return? So much emphasis is put on what this function takes as input, the return type is almost ignored.

The core function $() or jQuery() returns a jQuery object that is a collection of all DOM element objects that match the supplied selector rule. This jQuery object builds on top of the JavaScript Array API. For example, you can obtain the length:

$("p").length; //Number of paragraphs in the page.

To obtain a DOM element object in the collection, simply call get(index). The index is zero based. For example:

$("p").get(1).innerHTML; //Get the inner HTML of the second paragraph.

To call DOM API, you must get a DOM element from the collection. For example:

//Get all the p elements that are 
//children of the first div element.
$("div").get(0).getElementsByName("p");

//Following is an error. jQuery object is not a DOM element 
$("div").getElementsByName("p"); //Error!

While the jQuery object does not support DOM methods, it supports more methods than the JavaScript Array. These methods, like text() and css() form the heart of jQuery’s magic. Some of these methods have dual read and write use. For example, text(string) sets the inner text value of elements. While, text() returns the inner text. When you invoke a write method for the jQuery object, jQuery internally applies it to all DOM elements in the collection:

$("p").text("Hello!"); //Change text of all paragraphs to Hello!.

A getter function normally works on the first DOM element in the collection only.

$("p").text(); //Returns the text of the first paragraph only.

Converting Objects

We have already seen that to get a DOM object from a jQuery object, you call the get(index) method. But, how do we get a jQuery object for a DOM object? To convert a DOM element object into a jQuery collection do:

$(elementObject)

For example:

var e = document.getElementById("p1"); //Get the DOM element
var jObj = $(e); //Convert DOM element to jQuery object
jObj.hide(); //Call jQuery API

Which Object for Event Handlers?

The jQuery event handler registration functions like click() and hover() are just simple wrappers of the DOM event handler registration functions. In other words, these functions behave the same way as if you attached them using DOM’s addEventListener (or attachEvent for older IE). That means, the "this" keyword within the function points to the DOM element for which the function is being called. For example:

$("#myDiv").click(function() {

    this.innerHTML = "Clicked!"; //Straight DOM API
    $(this).css("background", "yellow"); //jQuery API

});

No Comments