ZNAG - Browsing jQuery

  1. jQAPI Air Application

    For the last year and a half I've been heavily exposed to a lot of open source software.
    It started out with a small conversation mentioning jQuery (Thanks Tim!), and since then I've been amazed by the open source community.

    The great thing about open source is that you can pay back to the people that created software that you like (Yes, the price is also nice, of course).

    I've been using jQAPI by Sebastian Senf (@mustardamus), which is an alternative (and in my personal opinion better) documentation for the jQuery API framework.

    Before that, I used the jQuery API Browser, which is also great, and provides a downloadable air file for offline browsing of the API.
    However, it's not been updated to 1.4.2, and lacks that kind of special touch that jQAPI has.

    So, after a couple of times of using jQAPI, I thought, heck, I know Air, I'll spend a couple of minutes hacking together a small air wrapper for jQAPI..

    Here are the results..

    Unfortunately, embedding the air installation badge in the post would have most likely to ruin any rss/atom subscriber reading this post, so we'll have to do with the link :)

    @mustardamus has been kind enough to both accept my fork changes, and to include both credits and a link at jQAPI(Thanks!).

    The source is at http://github.com/erikzaadi/jQAPI

     

    Enjoy!

    Erik

    Tags: jQuery, Github, jQAPI


  2. Compress Javascript with Google Closure Compiler in Visual Studio (with jQuery support)

    Google Closure Compiler is an amazing tool. Besides having the best compression rate (and being the official choice of jQuery) , it really alters the way you write javascript.

    When using the Advanced Optimization option, it forces you to write more concise code, exposing only what really matters to the global namespace.

    There's a lot more the be said in that matter, but that's material for a future post about how Google Closure Compiler changed the way I write jQuery plugins.

    For now, we'll only set up a quick way of invoking the Google Closure Compiler from within Visual Studio.

    Steps:
    1. Download the compiler.jar package and unzip it.
    2. Be sure to have at least the java run time installed (the java development kit will of course also do fine), both available here.
    3. In Visual Studio, click "Tools" -> "External Tools", then click "Add"
    4. Enter the title of your choice, and at the "Command", click the browse ("…") button and locate java.exe (should be something like this : C:\Program Files\Java\jdk1.6.0_18\bin\java.exe)
    5. At the "Arguments" enter the following:
      -jar X:\Path\To\YourDownloadedAndUnzipped\compiler.jar --js $(ItemPath) --js_output_file $(ItemDir)$(ItemFileName).min.js --compilation_level ADVANCED_OPTIMIZATIONS --summary_detail_level 3
    6. Check the "Use Output window" checkbox
    7. Click "Ok" to save your changes
    8. Open a javascript file and and click "Tools" -> "The Title You Gave To Google Closure Compiler"

    You should see the output folder popup with the following message "0 error(s), 0 warning(s)"
    That's if you don't have any errors in you javascript of course :)

    Caveats:

    The "ADVANCED_OPTIMIZATIONS" really changes a lot in your javascript, and it's worth reading through google's documentation in the matter if your javascript is broken after the compression.

    Making it work with jQuery:

    Since the "ADVANCED_OPTIMIZATIONS" will try to shorten all variables and function names, it breaks any jQuery plugin when compressed.

    To overcome this problem, we'll tell the Google Closure Compiler to use jQuery as an external reference, ensuring that the name of any jQuery function will be preserved.

    1. Download the latest uncompressed version of jQuery (1.4.2 at the time this post was written) to the folder you unzipped "compiler.jar" and call the file "jquery.js"
    2. Create a file called "withjQuery.bat" in the same folder and add the following content:
      @ECHO OFF


      SET InputFile=%1

      SET OutputFile=%2


      @ECHO *********************************************

      @ECHO Google Closure Compiler with jQuery Support 

      @ECHO Compiling : '%InputFile%'

      @ECHO *********************************************

      CALL "c:\Program Files\Java\jdk1.6.0_18\bin\java.exe" -jar X:\Path\To\YourDownloadedAndUnzipped\compiler.jar --js %InputFile% --js_output_file %OutputFile% --compilation_level ADVANCED_OPTIMIZATIONS --summary_detail_level 3 --warning_level QUIET --externs X:\Path\To\YourDownloadedAndUnzipped\jquery.js

      @ECHO *********************************************

      @ECHO Build Complete

      @ECHO *********************************************
    3. Add another External Tool as before, this time, choose the .bat file you created as "Command"
    4. As "Arguments" enter :
      $(ItemPath) $(ItemDir)$(ItemFileName).min.js
    5. Be sure to check the "Use Output window" checkbox as before
    Small note:

    You might want to integrate the Google Closure Compiler as a build step instead of an External Tool as explained here, if so I hope the small tips above will help you do so!

    Give it a try!

     

    Erik

    Tags: Google Closure Compiler, jQuery, jQuery Plugins, Visual Studio


  3. Update - jQuery Print Element version 1.1 Released

     

    Change log:

    1. Fixed a bug (calculating the base href for embedding css when not using port 80, see issue).
    2. Added a small feature, the entire element is cloned, ensuring that all attributes are added to the element in the generated print page (see feature request ).

    Links:

    Download | Download (Minified) | Documentation | Issues (Report a bug) | Official jQuery Plugin Page

     

    By the way, all of my jQuery plugins have been tested with jQuery 1.4.1..

     

    Enjoy!

    Tags: jQuery Plugins, jQuery


  4. jQuery 1.4.1 vsdoc (Visual Studio 2008 IntelliSense)

     

    For those of you who can't install asp.net mvc 2 rc2, here are the vsdoc files for jQuery 1.4.1 :

     

    http://demos.erikzaadi.com/js/jquery-1.4.1-vsdoc.js

    http://demos.erikzaadi.com/js/jquery-1.4.1.min-vsdoc.js

     

    The release also includes the vsdoc files for the jQuery validate plugin:

     

    http://demos.erikzaadi.com/js/jquery.validate-vsdoc.js

    http://demos.erikzaadi.com/js/jquery-1.4.1.min-vsdoc.js

     

    Enjoy,

     

    Erik

    Tags: jQuery, aspnetmvc2, Visual Studio


  5. Asp.Net MVC Exception Handling with jQuery

    I stumbled upon this excellent post by Sumit :

    http://2leggedspider.wordpress.com/2009/12/22/handling-exceptions-using-jquery-and-asp-net-mvc/

     

    I thought the idea was great, but the fact that you need to parse it as JSON bothered me.

     

    Since the information needed is only the status code, stack trace and error message, it seemed more appropriate for me to use the existing http response parts that are designed to pass those values.

     

    For the impatient:

    Demo | Source

     

    [Update] Altered the code with @Neal, and @Colin's feedback..

     

    I created a filter that inherits the default [HandleError] Attribute.

     

    public class HandleErrorWithAjaxFilter : HandleErrorAttribute
    {
        public bool ShowStackTraceIfNotDebug { getset}
        public override void OnException(ExceptionContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                var content = ShowStackTraceIfNotDebug ||
                                filterContext.HttpContext.IsDebuggingEnabled ?
                                    filterContext.Exception.StackTrace :
                                    string.Empty;
                filterContext.Result = new ContentResult
                {
                    ContentType = "text/plain",//Thanks Colin
                    Content = content
                };
                filterContext.HttpContext.Response.Status =
                    "500 " + filterContext.Exception.Message
                    .Replace("\r"" ")
                    .Replace("\n"" ");
                filterContext.ExceptionHandled = true;
                filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
            }
            else
            {
                base.OnException(filterContext);
            }
        }
    }


    Note:

        The typical usage would be to decorate the controller with the[HandleErrorWithAjaxFilter]attribute.

        However, for the sake of the example, the actions are decorated separately to show the different override usages. 

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [ErrorsForAjax.Models.HandleErrorWithAjaxFilter]
        public ActionResult ThrowError()
        {
            throw new Exception("This is the error message");
        }

        [ErrorsForAjax.Models.HandleErrorWithAjaxFilter(ShowStackTraceIfNotDebug = true)]
        public ActionResult ThrowErrorWithStackTrace()
        {
            throw new Exception("This is another error message");
        }
    }

     

    The filter detects if the request came from Ajax, and if so returns a more slim response, allowing me to capture it in the jQuery ajax method's error handler:

     

    $(function() {
        $("button").click(function() {
            $.ajax({ error: function(xhr, status, error) {
                    xhr.statusText; //ErrorMessage
                    xhr.responseText; //StackTrace (if debug or overridden)
                    xhr.status; //Numeric status code
                },
                    url: '/SomeUrlThatMightThrowAnError'
                });
            });
            return false;
        });
    });

     

     

    Demo | Source

     

    Thanks again to Sumit for the great idea, and to Neal and Colin for the feedback.

     

    Erik

    Tags: aspnetmvc, asp.net mvc, jQuery


  6. jQuery Console Plug-in

    Prelude [skip]

    A typical scenario for me when I start a new web site, is to include JavaScript snippets from previous sites.

    I usually get to a stage where need to solve problem that think I’ve solved before.
    Then, after a dark era for about 5 minutes of trying to actually remember when and where the solution is, I copy it to the new site.

    Each time I keep telling myself that I need to create some kind of template for those typical snippets I always end up adding.

    I wrote this jQuery plug-in since it’s one of the more common snippets I kept using.

    Every web developer out there is familiar with the amazing FireBug plug-in for FireFox, and probably also with the great logging features such as :


    console.log('something to log');


    This is a great feature for debugging your JavaScripts, in fact, it’s a real life saver.

    As you can’t really leave the FireFox specific syntax to throw errors in say… IE6, you’d usually end up writing something like this in your project :


    function LogToConsole(MessageOrObject){

      if (typeof(window['console']) != 'undefined'){

        console.log(MessageOrObject);

      }

    }


    Now that’s fine, but it limits you to debugging only in Firefox, which of course is never enough.
    Other browsers also have this feature, however, some with slightly different syntax.

    Chrome’s JavaScript debugger is quite useful (Ctrl + Shift + J), and it also supports console.log.
    So does Safari’s Developer (Which you need to enable in Settings –> Advanced, then Ctrl + Alt + I).
    Surprisingly enough, even Internet Explorer 8’s developer (F12) uses the same syntax.
    Opera’s DragonFly (Tools –> Advanced –> Developer Tools) however use a totally different syntax :


    opera.postError({someLabel:'someValue'});


    The console object also exposes several more helpful functions for debugging, such as console.error, console.trace etc.
    These extra functions are not yet supported in a standard way in all browsers unfortunately.

    So what does this plug-in do?  

    Simply put, it enables you to do safe, cross browser logging to the console.

    Examples:

    To log any object to the console:


    $.Console.Log('message',['dsad','dasdas'],{orJSON:'312'});


    Or, for debugging:


    $.Console.Debug('message',['dsad','dasdas'],{orJSON:'312'});


    To log a selected element(s), this time using the Info function if available :


    $('selector').Console($.Console.functions.Info) 


    Here’s a list of all functions available in the $.Console.functions :

    • Log
    • Trace
    • Debug
    • Info
    • Warn
    • Error
    • Dir
    • DirXML
    • Group
    • GroupCollapsed
    • GroupEnd
    • Time
    • TimeEnd
    • Profile
    • ProfileEnd
    • Count

    Please see http://getfirebug.com/console.html for more details on each function.

    Where can I get it?

    Project Page : Sample PageFork the project at Github

    Enjoy,

    Erik

    Tags: jQuery Plugins, jQuery


  7. Update - jQuery Print Element Plugin version 1.0 Released

    Thanks to John and David for their contribution and valuable input.

    Version 1.0 has no new groundbreaking features, mostly bug fixes (see changelog).

    There’s a new documentation page explaining the available options, and a new sample page as well.

    As always, any feedback will be much appreciated, either as comments here at the blog,  as an issue at the issues section,  or a bug report at the official jQuery plugin page.

    Enjoy,

    Erik

    Tags: Github, jQuery Plugins, jQuery


  8. jQuery Late Loader Plugin

    Prelude

    When enhancing dynamic pages (no matter the server side language behind), jQuery is more than helpful.
    Especially since there’s loads of jQuery plugins out there, saving so much time and effort.
    When using javascripts in reoccurring user controls, controlling the added javascripts and css files from the server language is possible (to prevent duplicate loading), but in many cases adds bloated and hard to maintain code.
    Keeping the includes only in the markup is easier to maintain (IMHO), however might cause unneeded http requests to your scripts and css files, especially if you have a page with multiple reoccurring user controls.

    The Plugin

    This plugin will allow you to include scripts ands css files dynamically, with success and failure callbacks.

    Usage


    $.LateLoader = 

        {

            LoadScriptOrCSS: 

            /*

            Loads a javascript/css from the passed url if it wasn't previously loaded

             

            The parameter can either be a string with the wanted url( then the default

            params are used (See Defaults for more details)), or an option object 

            URL -> relative or absolute URL to your javascript/css 

            */


            IsScriptOrCSSLoaded:

            /*

            Returns true|false if a javascript/css is already loaded

            (via LoadScriptOrCSS)

            

            Parameters : 

            URL-> relative or absolute URL to your javascript/css 

            Type->'js' or 'css' (defaults to 'js')

            */


            GetLoadedScriptOrCSSs: 

            /*

            Returns an array of all loaded scripts (object with 2 arrays, css and js)

            */


            GetLoadedScriptOrCSSsByType:

            /*

            Returns an array of all loaded scripts/css according to the passed type

            

            Parameter : 

            Type->'js' or 'css' 

            */


            PluginDefaults:

            {

                ArrayDataKey: "LateLoaderDataKey", 

                      //Unique key used to identify the jQuery Data collection

                ElementToAttachDataTo: "body", 

                      //DOM object that hosts the jQuery Data collection

                RemoteTimeout: 1500 

                      //MS of timeout to wait for a remote script..

            },

            Defaults:

                {

                    URL: null, 

                      //Will be filled in by LoadScriptOrCSS's parameter

                    Type: 'js', 

                      // 'js' or 'css' (defaults to 'js')

                    LoadedCallBackFunction: null, 

                      // Called when the javascript/css is loaded (default is null)

                    ErrorCallBackFunction: null 

                      // Called when an error occurs (default is null)

                }

        }


    Where can you get it?

    Main project page | Sample Page | Wiki | Source

    What’s missing in it?

    Detecting remote css files that are missing are so far only supported in IE
    The plugin should scan the existing scripts / links includes as well as the data loaded by the plugin

    Got suggestions?

    I’d love to hear any feedback!

    Enjoy,

    Erik

    Tags: jQuery Plugins, jQuery


  9. Github Project Pages

    Prelude (skip)

    About two weeks ago I found out about an amazing free service that github has called github pages.
    This service allows you to host a static web site per public project you have on github, in addition to a site for your account (E.g. http://accountname.github.com).

    Besides having wizards that create the site for you (although I haven’t used that yet), github offers another very nice feature:
    Github automatically process submits to the site via Jekyll, which is a simple yet amazingly efficient static site/blog creator.

    Jekyll allows you to create templates based with variables written in YAML, and using Liquid to parse the templates, enabling you to write logic such as conditions and loops, making the static site more flexible and somewhat dynamic.

    All you need to do is to commit to a project branch called gh-pages.
    In case it’s the main account site, you simply push to the master branch of a project called accountname.github.com.

    Being a curios person that I am, this was perfect for me,
    Creating my own project pages was a great excuse for me to learn new skills such as ruby, YAML and Liquid.

    here are the results:

    http://erikzaadi.github.com 

    I’m posting my public projects on the site, which BTW, you can see on the github badge on the right on this blog, which is a part of http://erikzaadi.github.com/jQueryPlugins that also includes the Print Element Plugin I posted about before.

    The Wiki and Issues sections will remain at the regular github pages, but samples, download pages and posts regarding project updates will be done on the new site.

    The layout is not yet final, but any feedback would still be greatly appreciated.
    The site includes a small ode to jQuery , in form of a jQuery UI Theme switcher that you may notice on the top left part.

    As a small side note, it’s amazing how easy it is to use the jQuery themes once you understand their genial simplicity.
    By following a small set of rules (explained here), you can create a site that’s fully theme-able and flexible for design changes.
    But that’s material for another post..

    Enjoy,

    Erik

    Tags: Github, General, Personal, jQuery Plugins, jQuery


  10. jQuery Print Element Plugin

    [UPDATE - Version 1.0 released]

    Similar to those "utilicous" moments are the "I got to write a jQuery plugin that does this" moments..
    Had one of those a while ago, and the results were the jQuery Print Element Plugin.
    For those of you that are not familiar with jQuery, I mentioned it previously in an early post.

    So what does this plug-in do?

    Well, as per the title, it sends a jQuery selected element to the printer.
    So what's special about it?

    Well, I saw a few existing plug-ins around (Kudos again to PrintArea and this fellow for the inspiration), but they lacked the functionality I needed.
    And of course, I really wanted to write my first jQuery plug-in :-)

    The usage is rather strait forward:

    $("selector").printElement();
     
    Which will caused the selected jQuery objects html to be sent to the printer.

    There are two main modes you can use:

    Print from :
    1. Iframe (default, Pro: Hidden)
    2. Popup (Pro: shows the user a preview of what'll be printed)
    For more info, and more options, have a look at the Wiki, or at the official plug-in page at jQuery.
    Would love to hear any feedback, either here or at the issues section..
    Cheers,

    Erik

    Tags: jQuery Plugins, jQuery