How to Post a Tweet using JavaScript

In this post we will post a tweet using JavaScript. Let us assume we have a button like following

image

On click event of this button we want to post a tweet. For that we need to navigate to user to URL

image

After status we can put text to be tweeted. So on click event we need to navigate to this URL and append text to be tweeted. Very first we need to check whether tweet length is less than 140 or not. If it is more than 140 then we will show error message to user.

image

txttoTweet is variable containing text to be tweeted. In Else part we can tweet by redirecting to said URL as following,

image

Full code is as following,

<html>
<head>
 <title>
 </title>
 <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.1.js">
</script>
 <script type="text/javascript">
 $(document).ready(function () {
 $('#btnTweet').click(function (e) {
 alert('hello11');
 var textToTweet = "Hi I am tweeting from here";
 if (textToTweet.length > 140) {
 alert('Tweet should be less than 140 Chars');
 }
 else {
 var twtLink = 'http://twitter.com/home?status=' +encodeURIComponent(textToTweet);
 window.open(twtLink,'_blank');
 }
 });
 });

</script>
 <style type="text/css">
 #btnTweet {
 width: 159px;
 height: 38px;
 }
 </style>
</head>
 <body>
 <h1>tweet from debugmode</h1>
 <button id="btnTweet">Tweet</button>
 </body>
</html>

Some of the important point worth discussing here is as following,

  • Text to Tweet must be inside encodeURIComponet . Else you will get error.
  • Check Text to Tweet is less than 140 characters.
  • If you want can open windows as dialog also.

On running above script you should be getting output as following,

image

On click of Tweet button in next tab or windows as of your browser setting you will be asked to log in to Twitter, if not already logged in

image

On successfully sign in you should be able to tweet.

image

In this way you can tweet using JavaScript. I hope this post was useful. Thanks for reading.

Consuming WCF SOAP Service in Windows 8 Metro Application

In this post we will consume WCF SOAP Service in C#/XAML based Metro Application. This is level 100 post showing basic steps to create simple WCF Service and consume that in Metro Application.

Very first let us create a WCF Service using VS2012. Form File menu create a new project by choosing WCF Service Application project template from WCF tab.

image

Remove all the default code from IService1.cs and replace it with following code. In below service contract we are going to return a simple greeting message. From client a name as string will be input to the service and service will return a greeting message as string.

IService1.cs


using System.ServiceModel;
namespace ServiceToConsumeinMetro
{
 [ServiceContract]
 public interface IService1
 {

[OperationContract]
 string GreetingMessage(string name);

 }

}

Service is implemented as following. It is concatenating two string and returning it .

Service1.svc.cs


namespace ServiceToConsumeinMetro
{

 public class Service1 : IService1
 {
 public string GreetingMessage(string name)
 {
 return "Welcome to Metro Word " + name;
 }
 }
}

We will go with the default binding and will not configure anything in Web.Config. Leave Web.config as it is and press F5 to run and host created WCF service in local server. On successful running in your browser you should have below output.

image

Now let us create a Metro Application to consume this service. From File menu in VS 2012 choose Blank App project template from Windows Metro Style tab.

image

Next let us design the page. On the page we are going to put one TextBox, One Button and one TextBlock. User will enter Name in textbox and on the click event of the button service will be called. Returned output from service will be displayed in the textblock. Xaml is as following

MainPage.xaml


<Page
 x:Class="App1.MainPage"
 IsTabStop="false"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 xmlns:local="using:App1"
 xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
 mc:Ignorable="d">

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
 <Grid.RowDefinitions>
 <RowDefinition Height="200" />
 <RowDefinition Height="200" />
 <RowDefinition Height="200" />
 </Grid.RowDefinitions>
 <TextBox x:Name="txtName" Margin="286,25,583,113" />
 <Button x:Name="btnCallService" Content="Enter Name above and touch to call service" Height="100" Width="364" Grid.Row="1" Margin="367,10,0,90" Click="btnCallService_Click_1"/>
 <TextBlock x:Name="textResult" Grid.Row="2" FontSize="30" FontWeight="Bold" />
 </Grid>
</Page>

Next we need to add Service Reference in the Metro project. For that right click on Metro Application project Reference tab and select Add Service Reference

image

Add the reference as following. My metro application name is App1. If your Metro application name is XYZ then you will be adding XYZ.ServiceReference1 provided you have not changed reference name while adding it.

image

In Metro word everything is asynchronous. So we need to make async call to service. When you add reference automatically visual studio creates async function for you.

image

We can call this function from service as following

image

If you notice we have put await keyword before making a call to service. Since service is called in await manner so the function inside which we are calling service must be async. On click event of the button service can be called as following

image

Combining all discussion together code behind will look like as following

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using App1.ServiceReference1;

namespace App1
{

 public sealed partial class MainPage : Page
 {
 public MainPage()
 {
 this.InitializeComponent();
 }

protected override void OnNavigatedTo(NavigationEventArgs e)
 {
 }

private async void btnCallService_Click_1(object sender, RoutedEventArgs e)
 {
 Service1Client proxy = new Service1Client();
 string result = await proxy.GreetingMessageAsync(txtName.Text);
 textResult.Text = result;
 }
 }
}

On running you should be getting output as following

image

I am sorry for poor UI experience but any way making UI immersive was not purpose of this post. I hope now you know basic steps to consume WCF SOAP service in metro application.

Sharing on Facebook using JavaScript

Objective

In this post we will see how can integrate our application with Facebook. We will look into how a status, picture or video can be shared on Facebook wall using JavaScript.

Expected output is as following

image

Register Application to Facebook

Very first we need to register our app on Facebook. We can register that by navigating on following link.

https://developers.facebook.com/apps

Select option of Create New App. Provide App Name and App Namespace. We need to provide unique App name and App Namespace.

image

After that, we need to complete Security Check.

image

Once Application has been successfully registered, you will get App ID and App Secret ID as following,

image

Once we got the App ID and App Secret ID, we need to provide information about site or mobile web from where we are going to share on Facebook. There are two important points very important here.

  1. App Domains
  2. Site URL and Mobile Web URL

Since I am going to do this sample on local server, hence I have set AppDomains as localhost and Web Page URL or Mobile Web URL will be http://localhost:1461/ . So I have configured that as following. Make sure you configure your App Domains and Site URL/Mobile URL as of your application. For example if your site domain is XYZ then give App Domains as XYZ and Site URL http://XYZ/yourpage

image

As of now we have registered and configured application on Facebook. Next we need to write JavaScript code to share on Facebook.

Code to Share on Facebook

Let us put a button on page. On clicking of this button we will share status on Facebook.

clip_image002

Very first we need to initialize page for Facebook integration. Put following code just before closing <body> tag. Do not forget to replace Your App Id with your real app Id.

clip_image003

Now we need to add reference of following JavaScript file. Add these references in Head section of HTML.

clip_image005

Once all references being added we need to write code on click event of button to share something on Facebook. We can share Video, Status, and Picture. FB.ui function will be used to share. Different parameters of this function is explained as following

clip_image007

Now we can share status as following,

clip_image009

If you are not logged in to Facebook then you get prompted to login and then share as following,

clip_image012

clip_image013

clip_image014

In this way we can share status on the Facebook using JavaScript. Combining all the codes together as following


<html>
<head>
<title>
Share on Facebook
</title>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.1.js">
</script>
<script src="https://connect.facebook.net/en_US/all.js">
</script>
<script type="text/javascript">
 $(document).ready(function () {
 $('#shareonfacebook').click(function (e) {
 alert('hello9');
 e.preventDefault();
 FB.ui(
 {
 method: 'feed',
 name: 'DebugmodeEventPlans',
 link: 'http://localhost:1461/ShareonFB.html',
 caption: 'hey how is my Application ? tell me dude',
 description: 'hey how is my Application ?',
 message: ''
 });
 });
 });
</script>
</head>
<body>
<button id="shareonfacebook" >ShareOnFaceBook</button>

<script>
FB.init({
appId : 'urappid'
});
</script>
</body>
</html>

If you want to share a Video you can share it by giving Source vale and Picture values as following.

image

In this way we can share status on Facebook from JavaScript. I hope this post is useful. Thanks for reading.

Presented in Pune User Group event

On 16th June 2012 , I got an opportunity to present on Windows 8 Metro Dev for Pune User Group .  It was a descent event with almost 100 audience. I presented on the topic “Windows 8 Metro Application Development using HTML and WinJS” . Please find slides of the session below,

I hope you find it useful. Thanks.

Saving and Retrieving JavaScript object in HTMl5 Local Storage

Recently while working I had a requierment to save Javascript array in local storage of HTML5. Let us say array is as follwing we want to save in local storage.

var movieArray = [
{ title: "The Artist", picture: "images/TheArtist.jpg" },
{ title: "A Better Life", picture: "images/abetterlife.jpg" },
{ title: "Abduction", picture: "images/abduction.jpg" },
{ title: "African Cats", picture: "images/africancats.jpg" },
{ title: "Angel Crest", picture: "images/angelscrest.jpg" },
{ title: "Arthur", picture: "images/arthur.jpg" },
{ title: "Anonymous", picture: "images/anonymous.jpg" },
{ title: "A Dangerous Method", picture: "images/adangerousmethod.jpg" },
];

Before saving iterate through array and display in the console. We can display on console as following

clip_image002

To see console log in chrome browser press F12 and select console tab.

clip_image003

everything is fine as of now and we can go ahead and save the data in local storage as following ,

clip_image005

As of now we have save data and fetched as well. let us try to display fetched data

clip_image007

in output windows you will be getting some expected data as following,

clip_image008

on matching you will find that type of original array was object whereas type of retrieve data is as string. This is where problem lies that HTMl5 stores data as string. so before saving data you need to stringify the array object and after retrieving data you need to parse the string as JSON object. saving and retrieving will be modified as following

clip_image010

now if you print retrieved result you should be getting the expected output. Full code to save and retrieve is as following ,


var movieArray = [
{ title: "The Artist", picture: "images/TheArtist.jpg" },
{ title: "A Better Life", picture: "images/abetterlife.jpg" },
{ title: "Abduction", picture: "images/abduction.jpg" },
{ title: "African Cats", picture: "images/africancats.jpg" },
{ title: "Angel Crest", picture: "images/angelscrest.jpg" },
{ title: "Arthur", picture: "images/arthur.jpg" },
{ title: "Anonymous", picture: "images/anonymous.jpg" },
{ title: "A Dangerous Method", picture: "images/adangerousmethod.jpg" },
];
 console.log('typeof movieArray: ' + typeof movieArray);
 console.log('movieArray:');
 for (var p in movieArray) {
 console.log(p+':'+movieArray[p].title+'|'+movieArray[p].picture);
 }

localStorage.setItem('movieArray', JSON.stringify(movieArray));
 var retrievedMovieArray = JSON.parse(localStorage.getItem('movieArray'));

console.log('typeof retrievedMovieArray: ' + typeof retrievedMovieArray);
 console.log('retrievedMovieArray:');
 for (var p in retrievedMovieArray) {
 console.log(p +':'+ retrievedMovieArray[p].title +'|'+retrievedMovieArray[p].picture);
 }
 });

In this way we can save and retrieve Javascript object in local storage of HTML5. I hope this post is useful. Thanks for reading.

Detect Internet connection in HTML5

In this quick post we will detect whether browser is connected to Internet or not? There are two ways you can detect it

  1. By making a AJAX call and setting the TimeOut property
  2. Using HTML5

In HTML5 you can detect it as following,

image

This is supported in all modern browsers. In this way you can detect whether browser is connected to Internet or not.

Migrate HTML5 WinJS Metro Application project to VS2012

In this post we will migrate a Metro Project created in HTML5 and WinJS from VS11 to VS2012 RC.

Recently I upgraded my system to Windows 8 Release Preview. After upgrading Windows, I migrated VS to VS2012 RC. After successful installation of VS2012, I tried opening a HTML5 + WinJS project created in VS11. When I tried to build that project, I got below exception.

image

Exception was in file C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets

To remove this error what all you need to do is go to solution and remove old reference of Microsoft.WinJS

image

And then again try to rebuild the solution. You should not be getting any build error. Though after than if you run the project you will be getting errors like

image

This error implies that reference has been missing. To solve this we need to add new reference in the project. Add Windows Library for JavaScript 1.0 RC reference in the project. image

After adding reference you need to change the references on HTML. Currently your reference may look like as following

clip_image002

You need to change Microsoft.WinJS.0.6 to Microsoft.WinJS.1.0.RC. After changing references should look like as following

clip_image004

No go ahead and run the project. You should be not getting any error. In this way you can migrate HTML5 WinJS Metro project to VS2012.

I hope this post is useful. Thanks for reading.

Windows Phone Application Life Cycle and Fast Application Switching

What we will learn in this Article ?

  • Windows Phone terminology
  • Application Life Cycle
  • Fast Application Switching
  • Managing Page State

Windows Phone Terminologies

Application State

Application sate is application level Data. This Data may be returned by the service and being displayed in different view. For example a list of students being retuned by a service and on Page1 only students names are being displayed whereas on Page2 student names and age are being displayed. So Application State is a data returned by service and being displayed differently on different pages of the application.

Page State

It is common scenario that user fill some value on page and navigate from that page. On returning to the same page user expects persisted value on the page. Page state is visual persisted state of the page. For example on a page there is one text box and one check box. User has entered some value in text box and checked the check box. Value entered in the textbox and checked checkbox creates Page state of the page.

Tombstoning

It is process to persist data after application is terminated. Data can be persisted of an individual page or data can be persisted of state of whole application. When again user navigates back then application gets recreated and all the data persisted gets restored.

State Dictionary

Dictionary objects are used to store key/value pair. Dictionary in Windows phone is used to restore the Application state. At time of Tombstoning Dictionary gets preserved.

Application Life Cycle

Application life cycle of Windows Phone application says about different state of the application from launching to closing. User launches an application and application goes to running state. Due to launching of other application or on pressing of hardware start or search button application goes to dormant or tombstone state. Again on the launching of application, app gets activated from either dormant or tombstone state. Application can be closed by pressing of hardware back button.

Block diagram on Application Life Cycle events

image

Different events are as below. All events are written in App.Xaml.CS

Application Launching

clip_image002

Application Activated

clip_image004

Application Deactivated

clip_image006

Application Closing

clip_image008

As a developer it is must to have understanding of sequence of events get executed in Windows Phone application life cycle

Fast Application Switching

Windows Phone 7.5 operating system provides improved fast application switching over Windows Phone 7 operating system. Before we go into details of how FAS is better in Mango, let us first understand what is FAS?

Imagine application “A” is running and user launches a new application “B”. On pressing hardware back button user can return back to application “A”. If application “A” gets activated without “resuming “ screen then it can be termed as “ Fast Application Switching

In Windows Phone 7.5 version FAS is improved over Windows Phone 7 with introduction of new state in application life cycle called “Dormant state”. Whereas in Windows Phone 7.0 version there was no Dormant state and on deactivation application directly goes to Tombstone state.

In Windows Phone 7 flow of application was as below,

  • User deactivates application by pressing hardware start or search button
  • Application goes to tombstone state
  • Windows Phone 7 operating system saves information about application Navigation state and State Dictionary
  • Operating system terminates application thread and processes.
  • User again activates application by pressing hardware back button.
  • Operating system creates application thread and process.
  • Operating system restores memory state by retrieving saved value of Navigation state and state dictionary.

Due to above steps in Windows Phone 7 operating system user gets feeling that application was running in background and got resumed from there. However this is not true and operating system again creates application process and restores memory state. Creation of application process and restoration of application memory states take time and cause to slower application switching.

image

In Windows Phone 7.5 flow of application is as below,

  • User deactivates application by pressing hardware start or search button
  • Application goes to dormant state
  • Windows Phone 7.5 operating system preserve instance of the application
  • User again activates application by pressing hardware back button.
  • Operating system restores preserve instance and re activate application
  • If operating system runs low on the memory, it pushes application from dormant state to tombstone state.
  • If application is reactivating from tombstone state then it follows the same cycle as of Windows Phone 7 operation system.

image

Now you understand significant of dormant state for Fast Application switch. With introduction of dormant state in application life cycle, operating system preserve instance of the application in memory unless it is forced to release due to low memory. So at the time of application reactivation as a developer you need to check whether to restore the application or not? If application is reactivating from dormant state then there should not be restoration.

On Application Activated event you can check whether application is reactivating from dormant or tombstone state as below,


private void Application_Activated(object sender, ActivatedEventArgs e)
 {

if (e.IsApplicationInstancePreserved)
 {

// No need to restore the application.
 // Application is reactivating from dormant state
 }

else
 {
 // Need to restore the application.
 // Application is reactivating from tombstone state
 // Read state dictionary and Navigation state to restore memory state

}
 }

An Application gets closed by pressing hardware back button. And in that case application neither goes to dormant state or tombstone state. If there are multiple pages in application then user navigates between pages using hardware back button. However if on start page of application user press hardware back button then operating system will close the application. While closing application Application_Closing() events gets executed.

Maintaining Page State

Page state deals with transient data whereas Application State deals with Persistent Data.

Page state deals with preserving data binding of the user interface of the page. If application is reactivating from dormant state then there is no need of preserving the state of the page or in simple words data of the controls on page explicitly. However if application is reactivating from tombstone state then page data need to be preserved and restore explicitly.

To demonstrate how Page State works? I have designed page as below,

Let us put some control on the phone application page.

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

 <TextBox x:Name="txtValue" Height="100" Margin="12,37,58,470" />
 <CheckBox x:Name="chkValue" Height="100" Margin="251,144,0,364"
 HorizontalAlignment="Left" Width="134" />
 <Slider x:Name="sldValue" Value="30"
 Height="100" Margin="28,383,58,124" />

 </Grid>

There are three controls on the page. After tombstone, we need to preserve and restore value of these controls. Now we need to create properties for each control. We need to call NotifyPropertyChanged event in the setter of property to notify when value changed at the control. Control value would be bind with two ways binding with these properties. Eventually Data class will be as below,


&nbsp;

using System.Runtime.Serialization;
using System.ComponentModel;

namespace RestorePageState
{
 [DataContract]
 public class Data : INotifyPropertyChanged
 {

private string textValue;
 private bool chckValue;
 private double sliderValue;

public string TextValue
 {
 get
 {
 return textValue;

}
 set
 {
 textValue = value;
 NotifyPropertyChanged("TextValue");

}
 }

public bool ChckValue
 {
 get
 {
 return chckValue;

}
 set
 {
 chckValue = value;
 NotifyPropertyChanged("ChckValue");

}
 }
 public double SliderValue
 {
 get
 {
 return sliderValue;

}
 set
 {
 sliderValue = value;
 NotifyPropertyChanged("SliderValue");

}
 }
 public event PropertyChangedEventHandler PropertyChanged;
 private void NotifyPropertyChanged(string propertyName)
 {
 if (null != PropertyChanged)
 PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
 }

}
}

With Data Class in place we need to preserve state of the page. There are two checks to perform before preserving page state. First check to be done, whether application is reactivating from dormant state. If so then there is no need of restoring the state. To save the state of the page OnNavigatedFrom method instance of the Data need to be saved in the State dictionary as below,


protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
 {
 if (e.NavigationMode != System.Windows.Navigation.NavigationMode.Back)
 {
 State["Data"] = dataToBindControls;
 }
 }

In above code dataToBindControls is object of Data bind to the controls on the page. To restore the page OnNavigatedTo method state count need to checked as below.


protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
 {
 if (isNewInstanceofPage)
 {
 if (dataToBindControls == null)
 {
 if (State.Count > 0)
 {
 dataToBindControls = (Data)State["Data"];
 }
 else
 {
 dataToBindControls = new Data();
 }
 }
 DataContext = dataToBindControls;
 }
 isNewInstanceofPage = false;
 }

}

Essentially there are three tasks we are performing in above function

  • Checking if it is new instance of the page.
  • If yes then checking if value of data control [object of data class ] is null
  • If null then reading from the state else creating new instance of that.

Full source code behind to preserve page is as below,

using Microsoft.Phone.Controls;

namespace RestorePageState
{
 public partial class MainPage : PhoneApplicationPage
 {

 Data dataToBindControls;
 bool isNewInstanceofPage;

public MainPage()
 {
 InitializeComponent();
 isNewInstanceofPage = true;
 }

protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
 {
 if (e.NavigationMode != System.Windows.Navigation.NavigationMode.Back)
 {
 State["Data"] = dataToBindControls;
 }
 }

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
 {
 if (isNewInstanceofPage)
 {
 if (dataToBindControls == null)
 {
 if (State.Count > 0)
 {
 dataToBindControls = (Data)State["Data"];
 }
 else
 {
 dataToBindControls = new Data();
 }
 }
 DataContext = dataToBindControls;
 }
 isNewInstanceofPage = false;
 }

}
}

Last but not least data need to be bind to controls as below,


<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

 <TextBox x:Name="txtValue" Height="100" Margin="12,37,58,470"
 Text="{Binding TextValue,Mode=TwoWay}"/>
 <CheckBox x:Name="chkValue" Height="100" Margin="251,144,0,364"
 HorizontalAlignment="Left" Width="134"
 IsChecked="{Binding ChckValue,Mode=TwoWay}"/>
 <Slider x:Name="sldValue"
 Height="100" Margin="28,383,58,124"
 Value="{Binding SliderValue,Mode=TwoWay}"/>

 </Grid>

In this way a page state can be preserved. Before debugging last step we need to perform is enable Tombstone upon deactivation while debugging in the properties page. There may be other approach to preserve state as below,

  • Creating extension method for page class
  • Create helper class and call method of the class to save control’s data.

I will conclude with supporting above approach of Page State restore and retrieve for better encapsulation. Since each page is handling their own state so it is easy to separate the concern for pages individually.

First look of New Windows Azure Portal

I must say, I liked this new HTML5 based Windows Azure Portal. Once you login in Windows Azure Portal at the bottom you can find View the Preview Portal

image

You will be prompted to take a tour of new portal.

image

You will be getting dashboard as following,

image

You can see details of all the Hosted Service and Storage Account and SQL Azure database there. Details like

  • Type
  • Status
  • Subscription
  • Location

Is shown on the home page as following

image

There are four tabs in left side. By default All Items tab is selected. Other tabs are as following

image

If you want to get more details about Hosted Service then select Cloud Services tab and you will be getting much deeper details as following

image

In same way if you want finer lever details on SQL Azure database then select SQL DATABASES tab from left . You will be getting SQL Azure database details as following

image

If you want finer level details on Storage you can get by selecting Storage tab. You will be getting details as following

image

You can create following items by clicking new button in bottom

image

Items can be created as following

  • New Hosted Service
  • New Storage
  • New SQL Database
  • New Web Site
  • New Virtual Machine
  • New Network

image

There are some features might be disabled in your subscription. You will get following message when you select that feature. In my subscription Web Site, Virtual Machine and Network is not available and I get below message when I select them. Any time we can sign up for Preview Program.

image

While creating you will be having two options of QUICK CREATE or CUSTOM CREATE. Quick Create will create a cloud service by just specifying URL. Content deployment and configuration can be done later.

image

Custom Create will create cloud service by providing URL and optionally providing content employment and configuration.

image

You can manage keys and delete a service from the option given in bottom of the page.

clip_image001

In bottom you have option to get Help as well.

clip_image003

On clicking of HELP you will be getting various details and various operations.

clip_image005

In further blog post I will give more details of other features. Till then enjoy the new Azure Portal.

 

Learn jQuery Part3: How to Filter in jQuery

Filtering elements in jQuery is very vital. We may come across many requirements when we need to filter HTML Elements or jQuery object to a subset of element on different set of criteria. We may have to filter on basis of

  • Some selection criteria
  • On basis of HTML elements name
  • On basis of callback function

To ease our task jQuery provides sets of filtering functions. Some of the functions are as following,

image

Let us explore each function one by one.

.eq(index)

This returns list of elements matching the set criteria. We apply .eq on jQuery object. For example .eq can be applied on elements like <li>, <tr>, < div> etc. on basis of index it filters the jQuery object and returns set of matching elements as a new single jQuery object. To understand it better let us take an example. Assume we have following HTML

image

And we need to select Item5. We need to change background and color of this element. We can perform this in two steps.

Step1: Select <li> element and convert it to jQuery object

Step2: Apply filter to fetch required element and apply desired CSS

We can select Item5 either by class name or using tag name. In both case we will have to apply filter using .eq.

image

In above code both filters will be returning same element [5th element in< li>]. We are passing index as 4 when selecting element by tag. Since there are five <li> elements and index starts from 0, so we need to pass 4 as index in first case. However when we are selecting element as class name then we are passing index 2 since there are only 3 elements exist with same class name.

Complete example of above discussion is given below.

Example 1

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
 <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js">
 </script>
</head>
<body>
 <p>This is Test page for Filter in jQuery</p>

<ul>
 <li class='toselect'>Item 1</li>
 <li>Item 2</li>
 <li class='toselect'>Item 3</li>
 <li>Item 4</li>
 <li class='toselect'>Item 5 will be selected</li>
 </ul>
</body>
<script type="text/javascript">

$('document').ready(function () {
 alert('hello');
 $('li').eq(4).css('color', 'red');
 $('.toselect').eq(2).css('background-color', 'blue');
 });
 </script>
</html>

&nbsp;

When we run above code, we should be getting output as following,

clip_image001

.first

We apply .first on jQuery object {essentially can be HTML elements} and it returns first matching element as jQuery object. Let us take the same example we took earlier for .eq. if we want color of first <li> element to be changed then we can change that as following,

image

.first also works in same way of .eq. We need to select element then convert that to jQuery object and finally apply .first to fetch first element as jQuery object.

Complete example of above discussion is as following,

Example 2


<!DOCTYPE html>
<html>
<head>
<title>Test</title>
 <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js">
 </script>
</head>
<body>
 <p>This is Test page for Filter in jQuery</p>

<ul>
 <li class='toselect'>Item 1</li>
 <li>Item 2</li>
 <li class='toselect'>Item 3</li>
 <li>Item 4</li>
 <li class='toselect'>Item 5 will be selected</li>
 </ul>
</body>
<script type="text/javascript">

$('document').ready(function () {
 $('li').first().css('color', 'red');
 });
 </script>
</html>

We will be getting expected output as following,

clip_image001[6]

.last

We apply .last on jQuery object {essentially can be HTML elements} and it returns last matching element as jQuery object. Let us take the same example we took earlier for .eq. if we want color of last <li> element to be changed then we can change that as following,

image

.last also works in same way of .eq. We need to select element then convert that to jQuery object and finally apply .last to fetch last element as jQuery object.

Complete example of above discussion is as following,

Example 3


<!DOCTYPE html>
<html>
<head>
<title>Test</title>
 <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js">
 </script>
</head>
<body>
 <p>This is Test page for Filter in jQuery</p>

 <ul>
 <li class='toselect'>Item 1</li>
 <li>Item 2</li>
 <li class='toselect'>Item 3</li>
 <li>Item 4</li>
 <li class='toselect'>Item 5 will be selected</li>
 </ul>
</body>
<script type="text/javascript">

 $('document').ready(function () {
 $('li').last().css('color', 'red');
 });
 </script>
</html>

We will be getting expected output as following,

clip_image001[8]

.has()

We apply .has on jQuery object {essentially can be HTML elements} and it returns jQuery object from set of matching elements.

.has can take two types of input parameter. It can take either selector as string or HTML DOM Element. Given element will be matched and jQuery object will be returned from matched subset DOM elements.

For example consider following HTML

image

If we want to change background of div contains <ul> then in this scenario we can use has. We will select <div> has <ul> as following,

image

Complete example of above discussion is as following,

Example 4


<!DOCTYPE html>
<html>
<head>
<title>Test</title>
 <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js">
 </script>
</head>
<body>
 <p>This is Test page for Filter in jQuery</p>

<ul>
 <li class='toselect'>Item 1</li>
 <li>Item 2</li>
 <li class='toselect'>
 Item 3
 <ul>
 <li>3.1</li>
 <li>3.2</li>
 </ul>
 </li>
 <li>Item 4</li>
 <li class='toselect'>Item 5 will be selected1</li>
 </ul>
 <div>
 <ul>
 <li>p1</li>
 <li>p2</li>
 </ul>
 </div>
 <div>
 <p>
 This DIV is just like that
 </p>
 </div>
</body>
<script type="text/javascript">

$('document').ready(function () {
 $('li').has('ul').css('color', 'red');
 $('div').has('ul').css('background-color', 'blue');
 });
 </script>
</html>

We will be getting expected output as following,

clip_image001[10]

.map

We use .map to iterate through a jQuery object and apply a function on each element. .map is useful when we want to get or set values on collection of elements. For example we want to fetch values of all the input elements. .map returns array as output.

Let us suppose we want to fetch value of all <li> as comma separated from following HTML

image

We will apply .map function to <li> to fetch all the value as array and then we will apply joins on array to make values as comma separated.

image

Complete example of above discussion is as following,

Example 5


<!DOCTYPE html>
<html>
<head>
<title>Test</title>
 <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js">
 </script>
</head>
<body>
 <p>This is Test page for Filter in jQuery</p>

<ul>
 <li class='toselect'>Item 1</li>
 <li>Item 2</li>
 <li class='toselect'>Item 3</li>
 <li>Item 4</li>
 <li class='toselect'>Item 5 will be selected</li>
 </ul>
</body>
<script type="text/javascript">

$('document').ready(function () {

var r = $('li').map(function () {
 return $(this).text();
 }).get().join(',');
 alert(r);

 });
 </script>
</html>

We will be getting expected output as following,

clip_image001[12]

.not

We apply .not on a jQuery object to fetch elements which does not match the selector. .not can take four different types of input

  • Selector
  • jQuery object
  • Elements
  • Function

As an output it returns jQuery object.

Let us consider following HTML and we want to change background color of all the odd <li> elements.

image

We can change that as following,

image

Complete example of above discussion is as following,

Example 6


<!DOCTYPE html>
<html>
<head>
<title>Test</title>
 <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js">
 </script>
</head>
<body>
 <p>This is Test page for Filter in jQuery</p>

<ul>
 <li class='toselect'>Item 1</li>
 <li>Item 2</li>
 <li class='toselect'>Item 3</li>
 <li>Item 4</li>
 <li class='toselect'>Item 5 will be selected</li>
 </ul>
</body>
<script type="text/javascript">

$('document').ready(function () {

$('li').not(':even').css('background-color', 'red');
 });
 </script>
</html>

We will be getting expected output as following,

clip_image001[14]

.slice

.slice can be applied on a jQuery object. It returns subset of elements as jQuery object on basis of specified criteria. We pass index of first element and last element of the returned subset. If index of last element is not specified then .slice will return all the elements from index of start element.

Consider following HTML and we want to change background color of all the <li> after second element

image

We can change background color using .slice as following,

image

Complete example of above discussion is as following,

Example 7


<!DOCTYPE html>
<html>
<head>
<title>Test</title>
 <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js">
 </script>
</head>
<body>
 <p>This is Test page for Filter in jQuery</p>

<ul>
 <li class='toselect'>Item 1</li>
 <li>Item 2</li>
 <li class='toselect'>Item 3</li>
 <li>Item 4</li>
 <li class='toselect'>Item 5 will be selected</li>
 </ul>
</body>
<script type="text/javascript">

$('document').ready(function () {

$('li').slice(2).css('background-color', 'red');
 });
 </script>
</html>

We will get expected output as following,

clip_image001[16]

Conclusion

These are the jQuery functions we may be using to filter. Sometime we may have to apply more than one function together to filter to a specific subset of elements. I hope this post is useful. Thanks for reading.