2LeggedSpider

Coffee break

Posted in ASP.NET, Coffee Break, jquery, Microsoft, MVC by Sumit Thomas on March 2, 2012
Tagged with: , ,

Fun with jQuery clone() and animate()

Posted in CSS, jquery by Sumit Thomas on December 29, 2009

[tweetmeme]While going through the jQuery API documention, I realised that I have not tried my hands at many of its wonderful functions. So I thought of doing something creative with clone() and animate() functions. Here are the list of things I am going to do…

  1. Capture the user’s keypress event as they type and get the key value
  2. Create a clone of a hidden DIV element and change its text to the keypress value
  3. Place the new DIV elements one after the other and provide some random background color for each DIV element
  4. Provide a touch of animation to make it look nice 🙂

OK, here we go…

First lets create a simple CSS class for our DIV element.

        .letter
        {
            font-weight: bold;
            color: #fff;
            border: 1px solid #000;
            padding: 5px;
            width: 20px;
            height: 20px;
            left: 0;
            float: left;
        }

This will create a simple box of dimension 20 x 20 pixels with a black border.

Next, we will jump in to the jQuery code…

        var newDiv = ""; 
        var oldDiv = "";
        $(document).ready(function() {
            oldDiv = $("div.letter");
            oldDiv.hide();
        }).keypress(function(e) {
            if (e.which == 32 || (65 <= e.which && e.which <= 65 + 25) 
                                    || (97 <= e.which && e.which <= 97 + 25)) {

                //Create a random RGB value
                var rgb = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + 
                              (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';

                //Get the actual value of the key
                var c = String.fromCharCode(e.which);

                //Create a clone of the existing DIV and place the clone next to it.
                newDiv = oldDiv.clone().insertAfter(oldDiv);

                //Provide the new DIV with the Key value and use animate function to apply the bg color(rgb)
                newDiv.html(c)
                        .animate({ backgroundColor: rgb }, 5000)
			            .show();

                //Set the new DIV as the last DIV of the chain.
                oldDiv = newDiv;
            }
        });

That should do it! Here is the complete code…

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>JQ Show Hide</title>
    <style type="text/css">
        .letter
        {
            font-weight: bold;
            color: #fff;
            border: 1px solid #000;
            padding: 5px;
            width: 20px;
            height: 20px;
            left: 0;
            float: left;
        }
    </style>

    <script type="text/javascript" src="http://www.google.com/jsapi"></script>

    <script type="text/javascript">
        google.load("jquery", "1.3.2");
        google.load("jqueryui", "1.5.2");
    </script>

    <script type="text/javascript">
        var newDiv = "";
        var oldDiv = "";
        $(document).ready(function() {
            oldDiv = $("div.letter");
            oldDiv.hide();
        }).keypress(function(e) {
            if (e.which == 32 || (65 <= e.which && e.which <= 65 + 25) || (97 <= e.which && e.which <= 97 + 25)) {
                var rgb = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) +
')';
                var c = String.fromCharCode(e.which);
                newDiv = oldDiv.clone().insertAfter(oldDiv);

                newDiv.html(document.createTextNode(c))
                        .animate({ backgroundColor: rgb }, 5000)
			            .show();

                oldDiv = newDiv;
            }
        });
        
 
    </script>

</head>
<body>
    <div class="letter" />
</body>
</html>

If you run the code, here is what you will see…

jQuery Animation

Let me know what you think 🙂

jQuery Show/Hide Content

Posted in jquery by Sumit Thomas on December 28, 2009

[tweetmeme]Here is a technique I normally use to show/hide a content in a div tag. This is quite an useful UI technique in situations where you have to show a Master-Child data, where the child data will be hidden initially and will be shown on demand on click of a image or button.

Lets say I have a web page which will have the following HTML output…

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>JQ Show Hide</title>
</head>
<body>
    <a href="javascript://" title="#content-1" class="toggle">
        <img src="images/plus.png" border="0" />
        Another URL Shortener and it is from Google </a>
    <div id="content-1" class="content">
        Goo.gl is Google’s version of URL Shortening service. Unlike its counterpart tinyurl.com
        or bit.ly, Goo.gl is not a stand alone tool to generate short URLs. For now, the
        only way you can shorten a URL using Goo.gl is by using the Google Toolbar or if
        you have a Feedburner account, integrate your Feedburner feeds with your Twitter
        account.
    </div>
</body>
</html>

Here I have a clickable Title Another URL Shortener and it is from Google and an Image followed by a content inside a div tag. To provide a better user experience we’ll set ourselves the following tasks…

  1. The content inside the DIV tag should be hidden when the page loads
  2. On clicking the Title or the Image, the content should slide down. On clicking again, it should toggle back to hidden state.
  3. The Image should change from plus to minus and vice-versa during the toggle.

Lets create a simple style sheet to perk up the look of the page.

        .toggle
        {
            font-size: large;
        }
        .toggle img
        {
            border-style: none;
        }
        .content
        {
            display: none;
            font-size: small;
        }

After adding a couple of content, our page will look like this…

Master Child Content

Finally, lets write the jQuery code to handle tasks 2 and 3

        $(document).ready(function() {
            $("a.toggle").click(function() {
                var img = $(this).find("img"); //get a handle of the image tag inside title link
                var src = $(img).attr("src"); //get the source of the image 

                //toggle the source of the image to show either plus/minus
                if (src.endsWith("plus.png"))
                    src = src.replace('plus.png', 'minus.png');
                else
                    src = src.replace('minus.png', 'plus.png');

                $(img).attr("src", src);
                
                //get the title of the anchor tag which corresponds to the id of the content div
                var content = $(this).attr("title"); 
                //toggle the display of the content div
                $(content).slideToggle();
            });
        });

        String.prototype.endsWith = function(str) {
            return this.lastIndexOf(str) == this.length - str.length;  
        }

endsWith is a custom javascript function which checks if a string ends with a given substring. This is useful in our case to check if the image source ends with plus.png or minus.png

Putting it all together, our final output will be as follows…

Master Child Content

Let me know if there is a better way of doing this.

Hope you found it useful! Happy jQuerying!

Tagged with: , ,

Handling Exceptions using jQuery and ASP.NET MVC

Posted in AJAX, ASPNETMVC, jquery by Sumit Thomas on December 22, 2009

[tweetmeme style=”compact”] Using AJAX has become one of the de facto practices in many web based RIAs. The use of jQuery is on the rise in many web applications, especially the ones built using ASP.NET MVC. Making AJAX calls using jQuery is quick and easy. A typical web request can have an expected response or an exception. It is therefore important to catch exceptions when we make any AJAX calls so that we can show some message which makes sense to the user.

Lets begin with our Controller. Create the following method to throw JSON version of the exception.

        private JsonResult ThrowJSONError(Exception e)
        {
            Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
            //Log your exception
            return Json(new { Message = e.Message});
        }

Specifying the StatusCode as HttpStatusCode.BadRequest or HttpStatusCode.InternalServerError or simply 500 will let the javascript know that there is something wrong in the response.

Lets create an ActionMethod to throw an exception which we will catch using jQuery.

        public ActionResult DivideByZero()
        {
            try
            {
                throw new DivideByZeroException();
            }
            catch (DivideByZeroException e)
            {
                return ThrowJSONError(e);
            }

        }

The above method will throw a DivideByZeroException which will be converted to a JSON string in the catch block and returned to the caller. Lets write the jQuery code to call the ActionMethod.

        $(document).ready(function() {
            $.ajax({
                type: "GET",
                url: "AJAX/DivideByZero",
                dataType: "json",
                success: function(data) {
                    if (data) {
                        alert("Success!!!");
                    }
                }, error: function(xhr, status, error) {
                    DisplayError(xhr);
                }
            });
        });

        function DisplayError(xhr) {
            var msg = JSON.parse(xhr.responseText);
            alert(msg.Message);
        }

Here we are making a call to the DivideByZero ActionMethod. Obviously the exception will be thrown,which will be caught in the error block. The responseText is a string of serialized data, which will not be useful unless we parse it to JSON. We can use the native JSON parser available in the latest browser. But, this as I found out is not helpful in IE 7 or lower. Fortunately, there is a useful library at JSON.org that can parse the responseText to JSON.

Let me know if there are better ways of handling exceptions in jQuery.

Hope you found it useful!

Tagged with: , ,

Enabling jQuery Intellisense in VS 2008

Posted in jquery by Sumit Thomas on December 18, 2009

[tweetmeme style=”compact”]This post is for all my friends who still don’t have jQuery intellisense enabled in their VS 2008. This came as a shock to my when one my colleagues asked me how come your VS has jQuery intellisense and mine does not?

So here is how you get it….

1) Download and install VS 2008 SP1 from here

2) Download and install the VS 2008 Patch from here. This patch helps VS 2008 check for -vsdoc.js files when a JavaScript file is in use and drive the JS intellisense engine.

VSDOC.js

jquery-1.3.2-vsdoc.js file is available in the Scripts folder of your ASP.NET MVC Web Application by default. If you don’t find it there then download it from here

That should do it!

Tagged with: , ,

Generating a Shorter URL using bit.ly API and jQuery

Posted in AJAX, jquery by Sumit Thomas on December 18, 2009

[tweetmeme style=”compact”]Here is a simple jQuery script to generate shorter URL using the bit.ly API.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>URL Shortening</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function() {
            $("#btnShort").click(function() {
                var longUrl = $("#longUrl").val();
                var shortUrl = $("#shortUrl");
                shortUrl.html("Loading...");
                var params = {
                    version: "2.0.1",
                    longUrl: longUrl,
                    login: "bitlyapidemo",
                    apiKey: "R_0da49e0a9118ff35f52f629d2d71bf07"
                };
 
                $.getJSON("http://api.bit.ly/shorten",
                { version: params.version, longUrl: params.longUrl, login: params.login, apiKey: params.apiKey },
                function(data) {
                    shortUrl.html(data.results[longUrl].shortUrl);
                });
            });
        });
 
    </script>

</head>
<body>
    <input type="text" id="longUrl" /><input type="button" id="btnShort" value="Shorten!" />
    <br />
    <div id="shortUrl" />
</body>
</html>

URL Shortening

You can go through the bit.ly API documentation and try out the remaining methods as well.

Tagged with: , ,

Check availability of Username using ASP.NET MVC and jQuery

Posted in AJAX, ASPNETMVC, jquery by Sumit Thomas on August 17, 2009

[tweetmeme style=”compact”]Here is a simple way to check if an Username is available using ASP.NET MVC and jQuery

Step 1: First lets create the XHTML markup for our View page(Index) as follows…

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Check if an Username already exists</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
//Your jQuery code will come here
</script>
</head>
 
<body>
    Enter a Username: <br />
    <input type="text" id="txtUsername" />
    <input type="button" id="btnCheck" value="Check!" />
    <div id="divStatus" />
</body>
</html>

So your view will look like this…

jQuery Username check

Step 2: Create a Controller class ‘UniqueNameController’ or WhateverController as follows…

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MyMVCTrials.Controllers
{
    [HandleError]
    public class UniqueNameController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public JsonResult CheckName(FormCollection form)
        {
            System.Threading.Thread.Sleep(3000);
            string name = form["username"];

            if (name.Equals("Sumit")) 
                return Json(false);
            return Json(true);
        }
    }
}

The Action Method CheckName contains the logic to check if the Username provided already exists or not. The code provided here is only for demo. Thread.Sleep(3000) will simulate a delay as if to show that the application is working really hard to find out if the username exists or not. REMOVE that line when you are writing the actual code to check the username against a database or Web service.

NOTE: The return value need not be a JsonResult. You can change it to ActionResult and return some string value to indicate the success/failure of the call.

Step 3: Lets replace the comment Your jQuery code will come here from our view with the following jQuery code…

        $(document).ready(function() {
            $("#btnCheck").click(function() {
                var name = $("#txtUsername").val(); //Value entered in the text box
                var status = $("#divStatus"); //DIV object to display the status message
                status.html("Checking....") //While our Thread works, we will show some message to indicate the progress

                //jQuery AJAX Post request
                $.post("/Home/CheckName", { username: name },
                    function(data) {
                        if (data == "true") {
                            status.html(name + " is available!");
                        } else {
                            status.html(name + " is not available!");
                        }
                    });
            });
        });

The code is very simple. The button click event makes an AJAX call to our ActionMethod CheckName and expects a response. The Thread.Sleep(3000) will delay the response for 3 seconds. The ActionMethod checks the value of the username and returns a JSON string for our AJAX call to handle.

We can fancy it up a bit by providing some color to our status messages using the jQuery addClass method. Putting it all together, our View will looks as follows…

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Check If Name Already Exists</title>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <style type="text/css">
        .green
        {
            color: Green;
        }
        .red
        {
            color: Red;
        }
    </style>
    <script type="text/javascript">
        $(document).ready(function() {
            $("#btnCheck").click(function() {
                var name = $("#txtUsername").val();
                var status = $("#divStatus");
                status.html("Checking....").removeClass();
                $.post("/Home/CheckName", { username: name },
                    function(data) {
                        if (data == "true") {
                            status.html(name + " is available!").addClass("green");
                        } else {
                            status.html(name + " is not available!").addClass("red");
                        }
                    });
            });
        });
    </script>
</head>
<body>
    Enter a Username:
    <br />
    <input type="text" id="txtUsername" />
    <input type="button" id="btnCheck" value="Check!" />
    <div id="divStatus" />
</body>
</html>

Checking the username
Progress

Username already exists
Not Available

Username is available
Available

There are different ways in which you can make AJAX requests using jQuery. For the detailed documentation check http://docs.jquery.com/Ajax. Hope it was useful!

Tagged with: , , ,