Tuesday, April 28, 2009

JQuery Basics

What is JQuery?
What does jQuery have to offer? First and foremost, jQuery has given me power over the Document Object Model (DOM)! jQuery Selectors are the greatest thing since sliced bread, no lie. Being able to EASILY find an object or group of objects in the DOM by ID, CSS Class, or by HTML Tag is something web developers have long needed.


To select an object from the DOM by ID would look like this:
$('#ID_Goes_Here')

To select an object from the DOM by CSS Class would look like this:
$('.CSS_Class_Name_Goes_Here')

To select an object from the DOM by HTML Tag would look like this:
$('Tag_Goes_Here')

For example, if I have a label that I want to be rendered but not visible I could create the label.

asp:label id="Label4" runat="server" cssclass="myLabel" text="This is " And later on in jQuery I can hide it like this.

$('#Label4').css('display', 'none');
It’s nice to be able to easily select an object and modify it, but what if you have a whole group of items you want to modify? With jQuery, you can EASILY loop through a collection of objects.


In this example I have a group of labels.

asp:label id="Label1" runat="server" cssclass="myLabel" text="This is "
asp:label id="Label2" runat="server" cssclass="myLabel" text="This is "
asp:label id="Label3" runat="server" cssclass="myLabel" text="This is "
asp:label id="Label4" runat="server" cssclass="myLabel" text="This is "
Now I want to update the text of each label to include its ID. I am going to loop through each object in the DOM with a CSS Class of .myLabel.

$('.myLabel').each(function() { $(this).append(this.id); });
What the jQuery code above does is execute a function that will append the object’s ID to its text value. Notice the Selector inside the function $(this). The syntax is used to find the loop’s current object in the DOM.

Now I have shown you some snippets here and there, let me show you what my page actually looks like.

script type="text/javascript"
function pageLoad() {
$('.myLabel').each(function() { $(this).append(this.id); });
$('.myLabel').css('color', '#FFFFFF').css('font-size', '30px');
$('#Label4').css('display', 'none');
$("#Panel1").html("(ul)(li)Item One(/li)(li)Item 2(/li)(/ul)");
}
script
asp:label id="Label1" runat="server" cssclass="myLabel" text="This is "

asp:label id="Label2" runat="server" cssclass="myLabel" text="This is "

asp:label id="Label3" runat="server" cssclass="myLabel" text="This is "

asp:label id="Label4" runat="server" cssclass="myLabel" text="This is "

asp:panel id="Panel1" runat="server"

No comments:

Post a Comment