This blog is moved to
http://amalhashim.wordpress.com
Showing posts with label JQuery. Show all posts
Showing posts with label JQuery. Show all posts

Wednesday, May 4, 2011

jQuery 1.6 Released

Sams Teach Yourself jQuery in 24 Hours
jQuery 1.6 is now available for download!

jQuery CDN:
Microsoft Ajax CDN:
You can read more about this on the following link: http://blog.jquery.com/2011/05/03/jquery-16-released/

Tuesday, March 9, 2010

jQuery A to Z – Part 2

As I promised in this part i am going to cover in depth of how to select/find elements from the DOM. One important thing I want to point out is about jQuery objects. We will use various methods for getting the DOM element. Once we get it, it will be in the form of jQuery object and this object is entirely different from the HTML element. And hence the properties and method will be different.

Selectors start with $() function which basically removes the need for a loop to access the group of elements as the objects are automatically looped and added by jQuery. Some examples

$(‘div’) – get all div elements in the document
$(‘#elementid’) – get all elements in the document having the given id
$(‘.classname’) – get all elements in the document having the class assigned to the given classname

Lets start Part 2 example by creating a website as we discussed in Part 1. Replace the code in default.aspx with the one provided below

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Part2._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>

<script src="jquery-1.3.2.js" type="text/javascript"></script>

<style type="text/css">
.horizontal
{
float: left;
list-style: none;
margin: 10px;
}
</style>
</head>

<script type="text/javascript" language="javascript">
</script>

<body>
<form id="form1" runat="server">
<ul id="os">
<li>Windows
<ul>
<li>DOS</li>
<li>Win 95</li>
<li>Win 98</li>
<li>Win ME</li>
<li>Win XP</li>
<li>Win Vista</li>
<li>Win 7</li>
</ul>
</li>
<li>Unix
<ul>
<li>Unix</li>
<li>Solaris</li>
<li>Linux</li>
</ul>
</li>
</ul>
</form>
</body>
</html>

The output of the website will be as follows

image

Now lets apply the Style “horizontal”. Add the below code in your page file.

<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#os > li').addClass('horizontal');
});
</script>

Here we are using the child combinator ( > ) to get all list items that is a child of an element with an ID of os (#os). The output of this query will make the page as follows

image

We can use the negation pseudo-class to identify all list items that do not have a class of horizontal. For that we will be using the following code.

$('#os li:not(.horizontal)').addClass('sub-level');


and the sub-level class will be
.sub-level
{
background-color: Yellow;
}

The jQuery will get all list items that do not have class horizontal, and for those list items it will apply the style sub-level. The output will be as shown below.

image

jQuery supports a set of basic XPath selectors. For selecting attributes jQuery uses XPath selectors. For example, for selecting all div which as width attributes

$('div[@width]')

Another scenario is if we want to get the element which contains another element

$('div[table]')

The above statements will get all the div’s which has a table.
Using XPath we can find if the attribute starts with a string as follows
$('a[@href^="mailto:"')
The above statement will get all anchor tag with attribute href starts with mailto

Similarly for finding the ending with
$('a[@href$=".aspx"')

This will find all anchor tags with href attribute ending with aspx extension
$('a[@href*="domain"')
Above query will find all anchor tags with href attribute containing the string domain anywhere.

All the selectors discussed return a set of elements, from the set if we want to access elements by index, we can use the Custom selector. Similar to array index, the index starts with 0.
$('div.horizontal:eq(0)')
Since CSS index is one based, in CSS selector we must use 1 to get the 1st element.
Two important custom selector included in jQuery are odd and even. For demonstrating this, let’s add a table element to our as shown below.
<table>
<tr>
<td>
SomeData1
</td>
<td>
SomeData2
</td>
</tr>
<tr>
<td>
SomeData3
</td>
<td>
SomeData4
</td>
</tr>
<tr>
<td>
SomeData5
</td>
<td>
SomeData6
</td>
</tr>
<tr>
<td>
SomeData7
</td>
<td>
SomeData8
</td>
</tr>
<tr>
<td>
SomeData9
</td>
<td>
SomeData10
</td>
</tr>
</table>

Include the below style for creating alternate rows

<style type="text/css">
.odd-style
{
background-color: Olive;
}
.even-style
{
background-color: Aqua;
}
</style>
 
Now let’s see how jQuery can apply those styles to the table.

<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('tr:odd').addClass('odd-style');
$('tr:even').addClass('even-style');
});
</script>

Here is the output

image
The first row index is 0 so its treated as even.

$('td:contains("somedata4")').addClass('bold');

will produce the following output
image
Let’s explore some DOM Traversal methods

$('tr').filter(':odd').addClass('odd-style');
This is another way to traverse the DOM and the impact is same as the statement we used for applying odd-style in previous scenario. I am going to add headers to our table by placing the following to the beginning of the table element.
<tr>
<th>Column1</th>
<th>Column2</th>
</tr>

Now the jQuery is modified as follows
$('th').parent().addClass('heading-style');
$('tr:not([th]):even').addClass('even-style');
$('tr:not([th]):odd').addClass('odd-style');
$('td:contains("SomeData3")').addClass('bold');
1st statement will get the parent of ‘th’ which will be the 1st tr and apply the style heading-style
2nd statement will get all tr even which don’t have a th element and applies the even-style
3rd statement will get all tr odd which don’t have a th element and applies the odd-style
4th statement remains the same as previous but only change is here i am making the 3rd cell bold. This is done to explain the next statement :-)
$('td:contains("SomeData3")').next().addClass('bold');

This will apply the style bold to the next cell following cell which has data “SomeData3”.

Some more samples.

$('td:contains("SomeData3")').siblings().addClass('bold');
$('td:contains("SomeData3")').parent().find('td:gt(0)')
.addClass('highlight');
$('td:contains("SomeData3")').parent().find('td').not(':contains("SomeData3")')).addClass('bold');
$('td:contains("SomeData3")').parent().find('td:eq(1)').addClass(
'bold').end().find('td:eq(2)').addClass('bold');

Hope you reached a level to understand the above statements. Else add it to your website and do some experiments :-)

Add one more column to our table and use the following jQuery

$('td:contains("SomeData3")')  //get every cell containing "SomeData3"
.parent()  //get its parent
.find('td:eq(1)')  //find inside the parent the 2nd cell
.addClass('bold')  //add the "bold" class to that cell
.end()  //revert back to the parent of the cell containing "SomeData3"
.find('td:eq(2)')  //find inside the parent the 3rd cell
.addClass('bold');  //add the "bold" class to that cell

If you want to find the tag name of an element with id “myId”, use the following statement

var myTag = $('#myId').get(0).tagName;
var myTag = $('#myId')[0].tagName;

Both will do the same job. This is the end of part 2. Hope it was a good learning. In part 3 I am planning to explain about Event and jQuery.

Sunday, March 7, 2010

jQuery A to Z – Part 1

jQuery is a powerful JavaScript library created by John Resig. Its an open source project. jQuery abstracts common web scripting situations. It has the following features
  • Easily traverse the DOM without writing large chunks of JavaScript.
  • Helps to change the CSS even after the page has been rendered.
  • Easily alter the page content with minimal code.
  • Efficient event handling.
  • Animations to the page.
  • Integrated with AJAX.
  • JavaScript tasks such as array manipulations and iterations.
  • Multiple actions in one line of code.
  • Library file size is minimal.
The official jQuery site is http://jquery.com. You can download the latest jQuery file from this site. For using jQuery in our site, we just need to provide the jQuery.js file path in script tags so it will get included.
Let’s create our first jQuery website. For this follow the steps outlined below.
  1. Open Visual Studio and add a new website, name is Part1
  2. Now we will add the jQuery js file we have downloaded. Right click the solution, Add Existing Item, open the folder where the file was downloaded. And click Ok.
  3. Now our solution will have the following structure.
     image
  4. Open default.aspx and paste the following code
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Part1._Default" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <title>Untitled Page</title>
    
    <script src="jquery-1.3.2.js" type="text/javascript"></script>
    
    <style type="text/css">        
    .oldstyle
    {
    margin: 0 2em;
    }
    .newstyle
    {
    font-style: italic;
    border: 1px solid #888;
    padding: 0.5em;
    color:Red;
    }
    </style>
    </head>
    
    <script type="text/javascript" language="javascript">
    $(document).ready(function() {
    $('.oldstyle').addClass('newstyle');
    });
    </script>
    
    <body>
    <form id="form1" runat="server">
    <div>
    <h1>
    Part 1</h1>
    <div>
    by Amal Hashim
    </div>
    <div class="oldstyle" id="part-1">
    Easily traverse the DOM without writing large chunks of JavaScript. Helps to change
    the CSS even after the page has been rendered. Easily alter the page content with
    minimal code. Efficient event handling. Animations to the page. Integrated with
    AJAX. JavaScript tasks such as array manipulations and iterations. Multiple actions
    in one line of code. Library file size is minimal.
    </div>
    </div>
    </form>
    </body>
    </html>
    

  5. Right click the default.aspx file and View in browser. image
The $ construct is used to select the document part. Here in our example $(‘oldstyle’) will find all part of the document having oldstyle. $() is a factory for the jQuery object. jQuery object encapsulates DOM elements. The .addClass() method helps to apply the newstyle for the selected oldstyle. The counterpart of addClass is removeClass() method. Our example will simply add newstyle.

Now the next question if when this code get’s executed. JavaScript is interpreted language, and it executes as and when it is encountered. But in our case, we want to have newstyle to be applied once the page gets loaded. One way to do this is using the onload event of the body tag. But in this case we will be modifying the HTML. But this is against the design pattern jQuery suggest, whose aim is to separate the tight coupling of HTML and JavaScript. To avoid this jQuery gives $(document).ready() construct. This does not require any HTML modification, on the other hand will get executed as and when the document is loaded. In our example we are using lambda function. Using the function keyword without method name, we are creating a method as and when its required. We mainly use lambda function as those methods are not being reused.

Hope all of you have read and had a good starting experience with jQuery. In Part 2 of this series i will cover in depth of how to select elements. jQuery supports XPath as well has jQuery’s own custom selector for traversing DOM. See you in Part 2.

Sunday, November 15, 2009

Image slide show using JQuery

In this article I am going to explain, how we can use JQuery for preparing a slid show using various images. You can download JQuery from the following link.

Download JQuery

Below is the aspx page content

<html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
<
title>Image slide show</title>
<
script type='text/javascript'
src="JQuery/jquery-1.3.2.min.js">
</
script>

<
script type="text/javascript">
$(function() {
var img = $("img.imgclass");
$(img).hide().eq(0).show();
var cnt = img.length;

setInterval(imgRotate, 5000);

function imgRotate() {
$(img).eq((img.length++) % cnt).fadeOut("slow", function() {
$(img).eq((img.length) % cnt)
.fadeIn("slow");
});
}
});
</script>
</
head>
<
body>
<
form id="form1" runat="server">
<
img src="Images/1.jpg" class="imgclass" alt="Image1"/>
<
img src="Images/10.jpg" class="imgclass" alt="Image2"/>
<
img src="Images/11.jpg" class="imgclass" alt="Image3"/>
</
form>
</
body>
</
html>

In the code what I am doing is straight forward. Get all img tags with class “imgclass”. Hide them initially. Every 5 second, call the method “imgRotate”. This method will fadeout the previous image and fade in the current image. Inside the form tag, you can add as many images you needed.

Hope this was helpful thumbs_up