Archive for category Tips

How to Check If jQuery Plugin is Loaded

A few days ago I was playing with jQuery plugin jTemplates. I had a tough time trying to get it working. As usual in such situation you can’t see obvious mistakes and instead you keep exploring all options which can possibly go wrong. During one of such exploration I was checking if  jTemplates has been correctly loaded. Of course real problem was completely different…  :)

But still, the code checking if plugin is loaded is very simple and thanks to it you have one less option to worry about. Here it is:

//check if jTemplates is loaded
if (!jQuery.fn.processTemplate) {
    alert("jTemplates is not loaded");
    return;
}

jTemplate has a function called processTemplate. If entire plugin was loaded correctly then this function is available. And this is exactly what is checked within if() statement. If for some reason plugin wasn’t loaded user will get an information: “jTemplates in not loaded”.

Of course you should use more user-friendly messages or deal with such problems in more elegant way. But nevertheless, checking if plugins are loaded should be a mandatory step for all developers. It doesn’t cost you much but in rare (hopefully) situations your site won’t crash because of lack of plugin which you expect to be loaded.

VN:F [1.9.14_1148]
Rating: 10.0/10 (3 votes cast)

1 Comment

Modules and AJAX Updates Every X Seconds

In this post I want to show you how easy you can achieve AJAX asynchronous updates with jQuery. Typical scenarios where such functionality is handy are all sorts of modules which you would like to update without reloading entire page like:

  • The latest tweeter updates
  • The latest comments
  • Currently logged in users, or number of users online
  • and so on …

In my example I will show you how to create module showing currently logged in users which will be updated asynchronously every 10 seconds.

1. Create ASP.NET Web Form Page which outputs JUST the module’s HTML

Here is ASP.NET code for my module:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CurrentlyLoggedInUsers.aspx.cs" Inherits="TestWebApp.Modules.CurrentlyLoggedInUsers" %>

<asp:Repeater ID="rptUsers" runat="server">
    <HeaderTemplate><div id="loggedInUsers"></HeaderTemplate>
    <ItemTemplate><a href="#"><%# Container.DataItem%></a>, </ItemTemplate>
    <FooterTemplate></div></FooterTemplate>
</asp:Repeater>

Generated at <%= DateTime.Now.ToLongTimeString() %>

And code behind code:

public partial class CurrentlyLoggedInUsers : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // dummy list of users
        var list = new List<String> { "john", "mark", "james", "mike", "rodney" };

        rptUsers.DataSource = list;
        rptUsers.DataBind();

        // simulate real life scenario where it takes some time to generate the list
        Thread.Sleep(2000);
    }
}

As you can see it’s nothing sophisticated, very simple HTML, Repeater and dummy list of users. Good base to check how this solution works and to build on top of that later on…

2. Module and jQuery code

On other pages, where module is supposed to be located, it’s required to have only a div tag inside of which module will be loaded by jQuery:

<div id="LoggedInUsersModule"></div>
<div id="LoggedInUsersModuleUpdateStatus"></div>

Second div tag will be used to indicate that AJAX update is in progress and is loading new data. It’s not a part of core solution but I think it’s something which is nice to have. It improves user’s experience.

And now jQuery code:

$(document).ready(function () {
    updateLoggedInUsersModule();
    window.setInterval(updateLoggedInUsersModule, 10000)
});

function updateLoggedInUsersModule() {
    $('#LoggedInUsersModuleUpdateStatus').html('Loading ...').fadeIn('fast');
    $('#LoggedInUsersModule').load('/Modules/CurrentlyLoggedInUsers.aspx', function(response, status, xhr) {
        $('#LoggedInUsersModuleUpdateStatus').fadeOut('fast');
    });
}

Explanation:

  • First 4 lines a responsible for setup. In the second line I’m manually calling updateLoggedInUsersModule() function to load initial data. I don’t want to wait 10 seconds to show something on a page.
  • window.setInterval() function is a JavaScript’s built-in function which will call function passed as a first parameter (updateLoggedInUsersModule() in my case) every 10 seconds (second parameter)
  • In 7th line I’m updating status by setting new inner HTML and then jQuery function fadeIn() will display the element.
  • 8th line is the most important line, load() function will load data from server and place it into selected element. In our case that will be div with id LoggedInUsersModule.
  • Last parameter of load() function is a callback function which will be invoked after loading the data. I used this place to hide ‘Loading …’ text and this way show that operation has ended with success. Text will be hidden by fading them to transparent thanks to fadeOut() function.

What next?

  • Nice thing about load() function is that you don’t necessarily have to use entire HTML generated by server. You can use jQuery selectors on that HTML in a following way: $(‘#LoggedInUsersModule’).load(‘/Modules/CurrentlyLoggedInUsers.aspx #loggedInUsers‘)
  • Please remember that modules like this, with AJAX updates done every X seconds will be heavily used so it’s essential to make sure that performance is not a problem. Use a lot of caching on server-side if necessary.
VN:F [1.9.14_1148]
Rating: 8.7/10 (3 votes cast)

No Comments

Custom Validators and Asynchronous Calls to Web Service with jQuery

Custom ASP.NET Validators give developers easy way to create validator which is tailored exactly to their needs. Last week I have encountered a scenario in which custom validator was a great solution. I was working on yet another registration form and my job was to validate if username and email address are unique with javascript. I have used Custom Validators for that because I was already using ASP.NET validators so I wanted to stick to one approach for all fields of the registration form. Within client side function I have used jQuery to call web service which will do the validation for me. The trick was to bring it all together and make sure that this solution works with asynchronous calls. Let me show it to you step by step.

1. Create validation Web Service

There are really no tricks regarding the web service. All that you have to remember is to make sure that following lines are uncommented:

// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]

Then add methods which jQuery will call to validate if username and email are unique and therefore available:

[WebMethod]
public bool IsUsernameAvailable(string username)
{
    Thread.Sleep(1000); // for tests only
    return !username.StartsWith("a");
}

[WebMethod]
public bool IsEmailAvailable(string email)
{
    Thread.Sleep(1000); // for tests only
    return email.StartsWith("a");
}

This is of course dummy implementation but I’m sure you get my point here. One thing worth noticing is that Sleep() method on Thread has been used. That’s because in real life scenario validation like this will require a call to a database so inevitably it will be slow. Thanks to Sleep() method I wanted to make sure that response is not instant and this way simulate real life scenario.

2. Custom Validator

Basic ASP.NET code consists of a field where users will enter username and custom validator for it:

<asp:Label ID="lblUsername" runat="server" AssociatedControlID="txbUsername" Text="Username" />
<asp:TextBox ID="txbUsername" runat="server"/>

<asp:CustomValidator
    ID="cuvUsernameAvailable"
    runat="server"
    ControlToValidate="txbUsername"
    Display="Dynamic"
    ClientValidationFunction="ValidateUsername"
    ErrorMessage="Username is not available!"/>

As you can see custom validator requires javascript function ValidateUsername to validate username.

3. Client Side function

Within javascript function I have used jQuery to call web service and this way delegate validation there. jQuery part looks like this:

ValidateUsernameWithWebService = function (username, successFunction) {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/Services/RegistrationDataValidationService.asmx/IsUsernameAvailable",
        data: "{'username':'" + username + "'}",
        dataType: "json",
        async: true,
        success: successFunction,
        error: function (result) {
            alert("Due to unexpected errors validation doesn't work");
        }
    });
}

A few words of explanation:

  • function expects two parameters – username (string) and callback function which will be called after web service invocation.
  • URL to the web service is /Services/RegistrationDataValidationService.asmx, and method which will be invoked is IsUsernameAvailable
  • async parameter is set to true so entire call will be done asynchronously

And finally the ValidateUsername function which will be called by the validator:

// variable to keep result of the last call to web service
var UsernameValidationResult;
// variable to keep information about username which was validated in the last call
var UsernameValidatorLastCheckValue;

ValidateUsername = function (source, args) {

    // detect validation triggered by form submission
    // prevent calls to web service in such scenario, return the previous result
    if (UsernameValidatorLastCheckValue == args.Value) {
        args.IsValid = UsernameValidationResult;
        return;
    }

    // async check with web service
    ValidateUsernameWithWebService(args.Value, function (result) {
        // following 2 lines are here to make sure
        // that on submit validator won't invoke call to webservice
        // it will reuse data from a call which was triggered by onChange event
        UsernameValidationResult = result.d;
        UsernameValidatorLastCheckValue = args.Value;

        // next three lines - inform validator about the result, update display
        source.isvalid = result.d;
        ValidatorUpdateDisplay(source);
        ValidatorUpdateIsValid();
    });
}

This part is a bit messy because you have to realize that validation and therefore this function will be called after entering username (onChange event) and when user click on submit button.

In the first case (onChange event) it’s fine to do the asynchronous call and get results after a second or two. However in case of form submission it’s not an option. It’s also worth noticing that in case of form submission username entered by the user hasn’t change, it was already validated. So it doesn’t make sense to validate it again. And that’s why in the above code I keep results of the last validation in the UsernameValidationResult and UsernameValidatorLastCheckValue variables.

I hope that it all make sense to you, if not then don’t hesitate to leave a comment. I will do my best to refine not clear areas. Also don’t hesitate to leave a comment even if everything is clear but you have a question or maybe something interesting to add. :)

VN:F [1.9.14_1148]
Rating: 10.0/10 (2 votes cast)

, ,

1 Comment

How To Empower ASP.NET Repeater With jQuery

As a ASP.NET developer I can imagine that you are using ASP.NET Repeater very often. It’s certainly true in my case. Repeater is probably the most useful control available in entire ASP.NET. It is great to output lists with custom template.

Here is a very simple example showing how to display list of strings as a HTML list. In code behind file I have to simply bind data to the repeater:

var list = new List() { "first point", "second point", "third point", "fourth point", "fifth point", "sixth point" };

rptList.DataSource = list;
rptList.DataBind();

And Repeater is defined in a following way:

<asp:Repeater ID="rptList" runat="server">
    <HeaderTemplate><ul></HeaderTemplate>
    <ItemTemplate>
        <li><%# Container.DataItem %></li>
    </ItemTemplate>
    <FooterTemplate></ul></FooterTemplate>
</asp:Repeater>

ASP.NET Repeater and dealing with CSS styles

To that point everything works great. However what was always problematic with Repeaters is manipulation with CSS styles. Quite typically there are requirements to set some custom class on a first and last element. Such requirements enforces changes in my clean code into something like this:

1. First let me update Repeater template:

<asp:Repeater ID="rptMagicList" runat="server">
    <HeaderTemplate><ul></HeaderTemplate>
    <ItemTemplate>
        <asp:Literal ID="litElement" runat="server" />
    </ItemTemplate>
    <FooterTemplate></ul></FooterTemplate>
</asp:Repeater>

2. Introduction of ASP.NET Literal means that binding will be done in code behind files:

private int elementsCount = 0;

protected void Page_Load(object sender, EventArgs e)
{
    var list = new List() { "first point", "second point", "third point", "fourth point", "fifth point", "sixth point" };

    // this is needed to figure out which element is the last one
    elementsCount = list.Count; 

    rptMagicList.ItemDataBound += rptMagicList_ItemDataBound;
    rptMagicList.DataSource = list;
    rptMagicList.DataBind();
}

void rptMagicList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        var currentElement = e.Item.DataItem as String;
        var litElement = e.Item.FindControl("litElement") as Literal;

        var cssClassName = String.Empty;
        if (e.Item.ItemIndex == 0) cssClassName = "first";
        if (e.Item.ItemIndex == elementsCount - 1) cssClassName = "last";

        litElement.Text = string.Format("<li class='{0}'>{1}</li>",cssClassName, currentElement);
    }
}

Of course this approach works. It’s also true that from developer to developer solution for this task may vary slightly. But I think you will agree that by adding one simple requirement we had to add lots of lines of monkey code. Let’s face it … this is not a rocket science, this code is trivial and after updating a few repeaters like this … you are sick of it.

So is there a better approach? I think there is – use strong side of ASP.NET Repeater to output list and strong side of jQuery to deal with custom CSS styles!

How to empower ASP.NET Repeater with jQuery

If you use Repeater + jQuery approach then there is no need to change ASP.NET code from initial example. All you have to do is to add JavaScript file with jQuery code:

$(document).ready(function () {
    $("ul.magicList > li:first").addClass("first");
    $("ul.magicList > li:last").addClass("last");
});

If you are new to jQuery and not sure what this code is doing, check my older posts. Everything is explained there in a simple way:

So to sum up … what are the benefits of this approach:

  • Less code – code which you write is an absolute minimum, no monkey code
  • Flexibility – jQuery has a lot to offer, ASP.NET has also a lot to offer — use strong sides of both technologies to get thinks done
  • Lack of hardcoded CSS classes in code behind files – this is also important, this way you don’t need a developer to change some purely UI related issues.
  • Part of HTML transformation is moved from server-side to client-side — if your servers have less work with one request, they can handle more requests
  • Richer UI – there are tones of jQuery plugins which you can use to improve user experience.
What are the alternatives? You can also stop using ASP.NET Repeater and switch to client side version – check how to implement client side repeater with jTemplates.
VN:F [1.9.14_1148]
Rating: 10.0/10 (2 votes cast)

,

No Comments

How To Use Basic jQuery Filters With HTML List (part 2)

In my previous post I have given you a few examples of the most basic jQuery filters. In this post I will dig a bit deeper to show you what else is possible.

Just to recap quickly, so far I have mentioned about following selectors:

  • :first – selects first element
  • :last – selects last element
  • : odd – selects all odd elements
  • :even – selects all even elements

And now a few new ones, but before I will jump to that, here is an HTML code which I use to play with:

<h2>
    Here is my magic list
</h2>
<p>
    <ul>
        <li>first point</li>
        <li>second point with an image: <img src="Images/icon_smile.gif" /></li>
        <li>third point</li>
        <li>fourth point</li>
        <li>fifth point</li>
        <li>sixth point</li>
    </ul>
</p>

Task 1: Our first taks is to add custom colour to the third and fifth element only, here is jQuery code which you can use:

$(document).ready(function () {
    $("ul.magicList > li:eq(2), ul.magicList > li:eq(4)").css("color", "red");
});

And here is the result:

basic jQuery filters

A few words of explanation:

  • li:eq(2) – our job was to select third element so you may ask why there is ’2′ passed as a paramater? That’s because index is zero-based. So first element has index 0, for second element index is 1 etc.
  • ul.magicList > li:eq(2), ul.magicList > li:eq(4)” – comma in the middle means logical OR. So it can be translated into: find third element OR fifth element.

Task 2: Now our objective is to select all elements starting from the second one. In other words … all except of the first one. There are two options which will give exactly the same effect:

$(document).ready(function () {
    $("ul.magicList > li:gt(0)").css("color", "red");
});

and second option:

$(document).ready(function () {
    $("ul.magicList > li:not(:first)").css("color", "red");
});

And here are the results:

jQuery filters and selectors

Explanation:

  • selector :not() allows you to invert selection, so you can select all elements that do not match the given selector, in our case :first
  • selector :gt() requires parameter, zero-based index. GT stands for “greather than”. In out case we want all elements where index is greather than 0. Hint: there is also another similar selector – lower than :lt() which works in analogical way.

Task 3: this one is more interesting … add custom colour for all elements which contain an image. Even though it may sound like a much more complicated job, in fact you can do it really easily:

$(document).ready(function () {
    // set custom style for all elements containing image
    $("ul.magicList > li:has(img)").css("color", "blue");
});

Explanation:

  • selector li:has(img) will return all LI elements conatining IMG tag. Of course you can use this selector to find any tag.

Task 4: the hardest task … add custom colour for every third element. So 3rd, 6th, 9th … elements should get a custom colour. jQuery doesn’t have a predefined selector for it, so in this case we have to implement it on our own. Luckily, it not a rocket science:

$(document).ready(function () {
    // set color only for every third element
    $("ul.magicList > li")
        .filter(function (index) { return index % 3 == 2; })
        .css("color", "red");});

Final result:

jQuery filters and selectors

Explanation:

  • after selecting all LI elements (“ul.magicList > li”) you can filter results with your own function which has to be passed as a parameter: filter(function (index) { return index % 3 == 2; })
  • your custom function is expected to return true for all elements that you want to include and false for element which you want to reject
  • parameter for your functions ‘index‘ is zero-based which means that for third element index is 2. 2 modulo 3 is 2. For sixth element index is 5, 5 modulo 3 is 2. You see how it works now?

I hope it all make sense to you. If not, leave a comment I will try to help! :)

VN:F [1.9.14_1148]
Rating: 10.0/10 (2 votes cast)

, ,

3 Comments

How To Use Basic jQuery Filters With HTML List

In this post I would like to show you how you can make use of jQuery selectors and filters to manipulate HTML list. Here is the starting HTML to play with:

<h2>
    Here is my magic list
</h2>
<p>
    <ul class="magicList">
        <li>first point</li>
        <li>second point</li>
        <li>third point</li>
        <li>fourth point</li>
        <li>fifth point</li>
        <li>sixth point</li>
    </ul>
</p>

Please note that on ul tag has a CSS class magicList defined. It’s useful to have a unique CSS class or ID defined because it makes writing selectors much easier. Now, having magicList CSS class defiend, you can use following jQuery selector to get list of all elements:

$(document).ready(function () {
    $("ul.magicList > li").css("color", "green");
});

A bit of explanation:

  • selector $(“ul.magicList”) will return all ul tags where CSS class equals ’magicList’
  • selector  $(“ul.magicList > li”) will return all li tags within ul tag where CSS class is ‘magicList’
  • css(“color”,”green”) – functions css() setts attribute color to provided value, in this case ‘green’

As a a result our HTML will look like this:

jQuery selectors and HTML list

Now, let’s try to make it a bit more sophisticated – odd elements can stay green, but even elements should be red :) Here is a jQuery code which can do that for you:

$(document).ready(function () {
    $("ul.magicList > li:odd").css("color", "green");
    $("ul.magicList > li:even").css("color", "red");
});

In the above case I have used jQuery filters to limit set of elements to the one which I need:

  • selector $(“ul.magicLIst > li”) will return all li tags and by using filter “:odd” it’s possible to take only odd elements and remove the even ones.
  • for even elements filter to use is “:even”

Okey, let’s add another requirement – first and last elemets should be blue. As you can probably guess already there are additional jQuery filters which will return for you first and last element:

$(document).ready(function () {
    $("ul.magicList > li:odd").css("color", "green");
    $("ul.magicList > li:even").css("color", "red");
    $("ul.magicList > li:last").css("color", "blue");
    $("ul.magicList > li:first").css("color", "blue");
});

And here is the final result:

jQuery filters and HTML list

In this post I wanted to give you an idea how powerful and useful jQuery is and how easy you can manipulate HTML list with it. Of course ,the same results you can achieved in many different ways within ASP.NET  but none of them is not as simple as jQuery one.

In the next posts you will find more advanced filters which means more fun and more options to get exactly what you need! :)

VN:F [1.9.14_1148]
Rating: 10.0/10 (2 votes cast)

, ,

2 Comments

How To Enable IntelliSense For jQuery in Visual Studio 2010

VS IntelliSense doesn't know anything about jQueryBy default IntelliSense in Visual Studio doesn’t know anything about jQuery. So for instance if you try get some help as soon as you type ‘$’ IntelliSense won’t suggest you anything useful. You can see that on the right.

Luckily enabling support for jQuery is very simple, I will show you how to do it in a few simple steps, but first let’s make sure that we are in the same starting point.

  1. Make sure that you have jQuery included in your project. If you created your application by choosing ‘ASP.NET Web Application’ then check folder Scripts. Look for files jquery-1.4.1.js or jquery-1.4.1.min.js – it should be there. If for some reason those files are not there, you can always download them form jQuery.com and manually add to the project.
  2. Make sure that jQuery documentation for Visual Studio is also included. Look for file jquery-1.4.1-vsdoc.js. Again it should in Scripts folder. If not, download for jQuery.com.

How to enable IntelliSense for jQuery

  1. Create new JScript file
  2. Drag & drop jquery-1.4.1-vsdoc.jsfile into the new javascript file.

    IntelliSense drag-and-drop

    when this is done your JS file should loke like this:

    /// <reference path="jquery-1.4.1-vsdoc.js" />
  3. Now you can start using IntelliSense, here are a few examples:

    jQuery IntelliSense
    jQuery IntelliSense 2

    jQuery IntelliSense 3

  4. Enjoy! :)

jQuery 1.6.2 Update

Currently the latest version if jQuery is version 1.6.2. Here you can download jQuery 1.6.2 documentation for Visual Studio.

VN:F [1.9.14_1148]
Rating: 7.7/10 (3 votes cast)

No Comments