Grails Custom JavaScript Function Usage Example Tutorial

While creating a menu for a Grails application today, I encountered a scenario which could be useful for beginners in Grails to learn and understand. I had to use JQuery and a custom function which will get invoked on click of a hyperlink. First, I designed a static HTML (without using Grails), and my Javascript code looked as shown below;
<script language='JavaScript' type='text/javascript' src='jquery-1.3.1.min.js'></script>
<script language='JavaScript'>
function showoutput(tab_id)
{
$("div[id^=custom]").hide();
$("#custom_"+tab_id).show();
} 
</script>
Now, this worked like a charm in both IE and Firefox.However, when I migrated this piece of code into my main.gsp file to keep the menu as a static layout in my Grails application, I got a function showoutput not found error at runtime. This DID NOT work for me in Firefox and Internet Explorer. After doing some analysis, I found the right method to invoke a Javascript function in Grails. I had to modify the code written for my test HTML page to the one as shown below, and then use the revised one in my main.gsp file.
        <script src="${resource(dir:'js', file:'jquery-1.3.1.min.js')}" type="text/javascript"></script>
        <g:javascript>
        function showoutput(tab_id)
        {
        $("div[id^=custom]").hide();
        $("#custom_"+tab_id).show();
        }
        </g:javascript>
Note that I'm using, g:javascript tag instead of the traditional one. At run time, Grails automatically converts this to proper Javascript notation as shown in the listing earlier. This got rid of the "Object Expected" error in both IE and Firefox, when this Javascript function was invoked over hyperlinks. An example Grails usage to trigger Javascript over hyperlinks on the "onclick" method is shown below;
<span><a onclick="myfunction('2')" href="javascript:void(0);">Order Details</a></span>
If you know any other way to modify this, share it with us in the comments section of this blog post.

2 comments:

  1. master!!!
    how to make related posts like in your blog?
    any show more load and previous!
    http://thinktibits.blogspot.com/2010/04/related-posts-blogger-integration.html
    i think thats script is different?

    cheers^^

    ReplyDelete
  2. @Beben

    I will post how to make this beautiful related post widget to blogger in my next post for sure. Just stay connected to my blog.

    ReplyDelete