Posts Tagged JQuery

Blissful Development

I have been working on a personal project to create a movie catalog database for our collection of movies. Yes, there are a handful of both desktop and web-based applications available to do this, though, they all seem to be lacking in one feature or another… and I needed an interesting useful project. This project has been one of my most enjoyable personal development projects; if you have ever seen my project graveyard, you know there have been quite a few that didn’t get very far for one reason or anther, usually time and/or complexity.

I owe my development-bliss on this project to something not usually found on modern software projects (at least in my experience)… simplicity. No, not simplicity of the project goals, but of the tools and the environment. For development I am using my favorite text editor, Notepad++, Cygwin (yes, I am doing this on Windows… I have not yet found a good solid text editor for Linux, perhaps I will have to make peace with vi)… and that’s it unless you want to count Firefox. But, wait… where is the IDE, the pile of plug-ins, and tools? Well, okay… I am also using Grails along with JQuery and JQueryUI. That’s the key… Grails.

With this environment I have been able to focus on building my application, not plumbing and other mundane details. I have an almost instant turn-around on changes to domain and controller classes, as well as a simple yet flexible syntax that allows for less IDE overhead, hence the text editor. Heck, most of my actual coding has been the HTML and JavaScript for the front-end; I have modified a few scaffold controller actions, and added a few of my own, which have all been simple and straightforward. It truly is a pleasant environment to work with.

Groovy itself is quite nice, providing a much more rich syntax while still maintaining total support of Java and Java syntax. One of the features of Grails I have always appreciated is that you always have Java to fall back on if you need a bit more performance, or access to something that cannot be accessed through Groovy itself. The two languages really coexist quite nicely.

I have the core JavaDocs pretty much burned into my memory (:-)), but I wonder how less-seasoned developers would find this setup. Without an IDE you don’t get code completion or the other helpful features that help to boost the productivity of more junior developers. It’s not meant to be a hard-core developer test; I am not into that kind of stuff. I am all about making development easier… and this just feels right for Grails (and Groovy).

Java web application development has gotten too hard somewhere along the way.

Popularity: 1% [?]

  • Share/Bookmark

Tags: , , , ,

Collapsible Divs With JQuery

I coded up a nice little collapsible-group side bar thingy using JQuery and it was surprisingly easy. Say you have a sidebar with collapsible group content such as:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<div class="container">
    <div class="group">
        <div class="group-title">Group A</div>
        <div class="group-content">
            This is where you would put the content for Group A.
        </div>
    </div>
    <div class="group">
        <div class="group-title">Group B</div>
        <div class="group-content">
            This is where you would put the content for Group B.
        </div>
    </div>
    <div class="group">
        <div class="group-title">Group C</div>
        <div class="group-content">
            This is where you would put the content for Group C.
        </div>
    </div>
</div>

where you have group block titles and group content that you want to be able to toggle the visibility of. With a couple lines of JavaScript and JQuery it’s a sinch:

1
2
3
$('div.group-title').bind('click',function(evt){
    $(evt.target).parent().find('.group-content').slideToggle(500);
});

which will be put inside an onload handler (also using JQuery). When the group title is clicked, the group-content block will toggle by sliding up or down in about half a second. With this model you can also place any number of these “components” on a page without the concern about event collision since the event handling is based on the click location.

Add in a little CSS and you end up with:

Popularity: 8% [?]

  • Share/Bookmark

Tags: , , ,

Accessing Ajax Response Headers

One way to handle error responses with Ajax requests is to add an HTTP Response Header to the response, denoting the resulting command status, while still returning content or data related to the error in the response. Generally when using Ajax calls you don’t want a raw exception or server error to bubble up to your JavaScript handlers.

Let’s say we have a simple quote service at “blurb.jsp”:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<%@page import="java.util.Random"%>
<%!
    private static final Random rng = new Random();
    private static final String[] quotes = {
        "I regret that I have but one life to live for my country.",
        "To be or not to be, that is the question...",
        "I drank what?",
        "I am what I am and that's all I am"
    };
%>
<%
    try {
       // WARNING: intentional random error below
        final String quote = quotes[rng.nextInt(quotes.length+1)];
       
        response.setContentType("text/plain");
        response.setHeader("X-Status","OK");
        out.write(quote);
       
    } catch(Exception e){
        response.setHeader("X-Status","ERR");
        out.write("Something bad has happened: " + e.getMessage());
    } finally {
        out.close();
    }
%>

All this does is setup some simple quote strings and randomly provide one of them as a text response. I have added an error condition by allowing the random number generated to exceed the maximum index of the array so that we can get a random error response. In both cases, success or failure, the response header “X-Status” is given a value of “OK” or “ERR” respectively to denote the type of response being sent.

Handling this response with Prototype is pretty simple:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<html>
    <head>
        <script type="text/javascript"
           src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js"></script>
        <script type="text/javascript">
            Event.observe(window,'load',function(){
                $('quote').observe('click',handleClick);
            });
           
            function handleClick(evt){
                new Ajax.Request('blurb.jsp', {
                    onSuccess: function(response) {
                        var quoteElt = $('quote');
                        if( 'ERR' == response.getHeader('X-G-Status') ){
                            quoteElt.setStyle({color:'red'});
                        } else {
                            quoteElt.setStyle({color:'black'});
                        }
                        quoteElt.update(response.responseText);
                    }
                });
            }
        </script>
    </head>
    <body>
   
        <blockquote id="quote" style="border:1px dashed green;padding:4px;">Click me for a quote...</blockquote>
   
    </body>
</html>

Basically, in your “onSuccess” handler function you just pull the header value out of the response object. You could conceivably do any kind of response handling you wanted for an “error” response. In the little demo, you will get a quote from the server each time you click on the quote box; successful quotes will be black, while errors will be in red text.

For the heck of it, I decided to try the same thing in JQuery (without making a whole separate post about it). I am just including the script sections, since they are the only difference:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<script type="text/javascript"
   src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
    jQuery(function(){
        $('#quote').bind('click',handleClick);
    });
   
    function handleClick(evt){
        var jqr = jQuery.get(
            'blurb.jsp',
            function(text){
                var quoteElt = $('#quote');
                if( 'ERR' == jqr.getResponseHeader('X-Status') ){
                    quoteElt.css('color','red');
                } else {
                    quoteElt.css('color','black');
                }
                quoteElt.html(text);
            },
            'text'
        );
    }
</script>

Surprisingly enough, this was a bit more difficult (or convoluted) to do with JQuery since JQuery does not seem to provide any wrapper access to the response itself. You have to use the XMLHTTPRequest object, which works fine but as you can see in the Ajax callback it leads to some interesting code; the jqr varible contains the request object and is used inside the callback function. It just feels a lot less clean.

Maybe I am not clear on how to use the JQuery Ajax support yet and I am missing something simple… or the developers of JQuery decided that since the times you actually need the response object itself are pretty limited, they could get away without providing direct access. Ultimately though, the support is there and that’s what’s really important.

Popularity: 2% [?]

  • Share/Bookmark

Tags: , , , ,

Highlight Text With JavaScript: JQuery

In my recent post about Highlighting Text With JavaScript I suggested that I should try doing the same functionality with JQuery.

So I did, and I am really starting to like JQuery. Below are the modifications to the HTML shown in the previous posting; basically you just swap out the two script elements in the Prototype version with those shown below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
    jQuery(function(){
        $('#content').bind('click',highlight);
    });
   
    function highlight(){
        var htm = $('#content').html();
        var str = '';
       
        jQuery.each( htm.split(' '), function(){
           if(jQuery.trim(this) != ''){
            str += this.replace('pick','<span>pick</span>');
           }
           str += ' ';
        });
       
        $('#content').html(str);
    }
</script>

JQuery does on-load event handling and event-handling in general, from what I have seen, in a very similar way to how Prototype does it. The highlight() function is a bit more complex in this version as JQuery does not seem to have the same level of String manipulation support out of the box; however, maybe I missed it in the documentation or perhaps there is a good plugin that adds better string handling.

This post is not really meant to compare the two libraries overall; it was more to satisfy my curiousity and get some practice with JQuery when solving a problem I have already solved with Prototype.

Popularity: 2% [?]

  • Share/Bookmark

Tags: , ,

Switch to our mobile site