jQuery Plugin Tutorial Part II - jQuery Basics

Before diving into developing a jQuery plugin, I decided to explain a bit about jQuery. If you are familiar with jQuery you can skip this part of the tutorial. jQuery as stated on the jQuery website, is a "write less do more JavaScript library". The most unique thing about jQuery is the jQuery selectors functionality.

Normally if we were to select an element using its "id" in JavaScript we would have to write
var element = document.getElementById("element-id");
but when using jQuery it is as simple as
var element = $("#element-id");

In order to set the class attribute of an element using JavaScript, we say
var element = document.getElementById("element-id");
element.setAttribute("class" , "class-name");
but when using jQuery, all we have to do is
$('#element-id').attr('class','class-name'); 

Another feature of jQuery is that you can chain functions in jQuery like follows.
$('#element-id').addClass('new-class').removeClass('old-class'); 

Not only can you select specific elements by id, but also you can select various other combinations.
$(".class-name")
selects all elements of a class.
$("img")
selects all elements of type "img".
So the code
$("img").addClass("class-name");
will add the class "class-name"  to all img elements.

By now you would have noticed that these are css selectors. But jQuery has its own selectors as well, such as the :animated selector.

Now let us look at how a plugin is invoked using jQuery. If you have included a date-picker plugin for jQuery, the usual way of invoking a date-picker would be
$("input-element").datepicker();
And you will have a date-picker that looks like the following.
Quite easy right? It was easy because some one else took the time and effort to write the functionality as a jQuery plugin. As you can see the benefit of writing this as a plugin is that it can be very easily reused. It is about writing such  a plugin that we are going to discuss in this tutorial.

No comments:

Post a Comment