2LeggedSpider

links for 2009-12-30

Posted in Daily Links by Sumit Thomas on December 30, 2009

Fun with jQuery clone() and animate()

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

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 :)

links for 2009-12-29

Posted in Daily Links by Sumit Thomas on December 29, 2009

jQuery Show/Hide Content

Posted in jquery by Sumit Thomas on December 28, 2009

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: , ,

links for 2009-12-28

Posted in Daily Links by Sumit Thomas on December 28, 2009

links for 2009-12-24

Posted in Daily Links by Sumit Thomas on December 24, 2009

links for 2009-12-23

Posted in Daily Links by Sumit Thomas on December 23, 2009

links for 2009-12-22

Posted in Daily Links by Sumit Thomas on December 22, 2009

Handling Exceptions using jQuery and ASP.NET MVC

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

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: , ,

YouTube says I have shorter URLs too!

Posted in technology by Sumit Thomas on December 22, 2009

Following Google’s launch of its Short URL service Goo.gl, its subsidiary Youtube has come out with its own Short URL service Youtu.be

YouTube’s intention for coming up with its own Short URL service is as per this blog to provide a shorter version of Youtube links.

To use youtu.be manually, simply take a URL like http://www.youtube.com/watch?v=FdeioVndUhs and replace the “http://www.youtube.com/watch?v=” with “http://youtu.be/” to get: http://youtu.be/FdeioVndUhs Plug that shorter URL into a browser, and you’ll see it redirects to that video.

Well it doesn’t look too short to me. The shorter version of http://www.youtube.com/watch?v=FdeioVndUhs in bit.ly is http://bit.ly/7Se5hu compared to Youtu.be’s http://youtu.be/FdeioVndUhs. The Video ID in YouTube links are very long and needs to be shortened further.

The big question for me though is why did YouTube come up with its own Shorter URLs when they could have used Goo.gl? Is it some kind of marketing technique or is it YouTube’s way of saying we have it too!

Whats next? Yah.oo?

Follow

Get every new post delivered to your Inbox.