Showing posts with label jquery. Show all posts
Showing posts with label jquery. Show all posts

Thursday, April 18, 2013

Just Another Frontend Boilerplate

Recently put together a frontend boilerplate with some latest 3rd party libraries makes into a checkout-and-ready-to-use boilerplate.  It has a configured built tool which you can use right away.  Also, it comes with a customize micro framework which you can take advantage of, but you can replace it with your own easily.

For more information, go to https://github.com/iroy2000/frontend-boilerplate

Frontend Boilerplate

This frontend boilerplate includes a customized mirco framework that combines some of the latest frontend library in the market. It comes with Jasmine as testing framework, plus build tool and build config.

Libraries Included

  • Backbone ( amd )
  • Backbone Localstorage
  • Underscore ( amd )
  • Twitter Bootstrap
  • Require-jQuery
  • Text ( RequireJS Plugin )
  • Modernizr
  • HTML5 Bolierplate ( partial )

Monday, April 1, 2013

IE error on feeding array of HTML elements to jquery html()

I was debugging a seemingly simple issues in IE ( but it turns out could be an inconsistent in javascript implantation ), which unsurprisingly works in other browsers.  When I trace the error, it was coming from the jquery library, and in which there is a native function call fragment.append(elem)

And this is my guess - the implementation of append() in IE doesn't really support an array of elements. Maybe I'm wrong, please let me know if that's a wrong guess.

There are so many ways to fix it, but one simple way is do a 'join' on your array before feeding to the jquery html()  function to append stuff.

Monday, April 2, 2012

jQuery how to scroll to particular line in textarea

Recently I was working with outputting formatted source code in a textarea, and the requirement is you have a control "sidebar", which is a list, that allow user to click on and the textarea will scroll to particular line accordingly.

In jQuery, when you use the below. the textarea will scroll to the top

$('.my_class_for_this_textarea').animate({ scrollTop: 0 });

However, in my case, the sidebar list only tells you the code is in line 100 for example.  How to make sure you tell jQuery to scroll to the correct line every time??

scrollTop  takes "pixels", and you need to find out your pixel of each line is. And the following is the formular.

$('.my_class_for_this_textarea').animate({
  scrollTop: my_relative_line_number * LINE_PIXEL
}); 

Thursday, October 13, 2011

jQuery Plugin Patterns

Here are some jQuery Plugin Patterns, the list is still expanding.  This post is mostly for my own reference, but just blog it here in case someone might be helped from this.

One note before you start doing your super fancy plugin.  The 'this' keyword in the immediate scope of the plugin is referring to the jQuery object, so there is no need to do $(this).  


Basic Form


  $.fn.yourPlugin = function(options, callback) {
    // ...
  };



Wrapped in Closure to create namespace

;(function($, window, undefined) {
  $.fn.yourPlugin = function(options, callback) {
    // ...
  };
})(jQuery, window);



Define multiple related functions (or related plugins) in one shot. 

;(function($, window, undefined) {
  $.extend($.fn, {
     yourPlugin: function() {
        // ...
     },
     yourSecondPlugin: function() {
        // ...
     }
  });
})(jQuery, window);


Prototype way

;(function($, window, undefined) {
  var pluginName = 'yourPlugin', pluginDefaultOptions = {};

  function Plugin(el, options) {
    this.element = el;
    this.options = $.extend({}, pluginDefaultOptions, options);
    this._name = pluginName;
    this.init();
  }  

  Plugin.prototype.init = function() {
    // ...
  }

  // make sure only one instance is instantiated
  $.fn[pluginName] = function ( options ) {
    return this.each(function () {
       if (!$.data(this, 'plugin_' + pluginName)) {
           $.data(this, 'plugin_' + pluginName,
           new Plugin( this, options ));
       }
    });
  }

})(jQuery, window);


Object Literal way

;(function($, window, undefined) {

    $.fn.pluginName = function(method) {

        var methods = {
            init : function(options) {
                this.pluginName.settings = $.extend({}, 
                                             this.pluginName.defaults, 
                                             options);
                return this.each(function() {
                    var $element = $(this), 
                         element = this;  
                    // ...
                });
            },

            my_public_method: function() {
                // ...
            }
        }

        var helpers = {
            my_private_method: function() {
                // ...
            }
        }

        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error( 'Method "' +  method + '" does not exist in pluginName plugin!');
        }
    }

    $.fn.pluginName.defaults = {
        foo: 'bar'
    }

    $.fn.pluginName.settings = {}

})(jQuery, window);



Modified Object Literal way

;(function($, window, undefined){
    $.fn.packagename = function(options, callback){
        
        var params = $.extend({},
                        $.fn.packagename.default_options, options), 
                        $that = $(this);
        
        if($.isFunction(options)){
            callback = options;
            options = {};
        } 
        
        var methods = {
            init: function() {
               // ... 
            }
        }
        
        methods.init.apply(this,[]);      
    }
    
    $.fn.packagename.default_options = {
       src: ".data" 
    }
})(jQuery, window);






Monday, September 26, 2011

Status Code 204 Bug in older jQuery

Recently debugging an old tool written partially in jQuery ( version 1.3.2 ), and found out that the ajax call always ends up going to the error() callback.  But when I ping the web service, it is returning 2XX which is totally fine.  And I kept tracing until I found out a bug in that version of jQuery, aha!

Hope this post help those who may have a chance maintaining tools that are developed using older version of jQuery.

Some blogs mentioned that it is the jQuery doesn't accept 204 as success. But when I traced the jQuery code, I saw that it actually accepts 204 as a success.  So "204" is not the main reason.  Look at the following code snippets :-

        httpSuccess: function( xhr ) {
                try {
                        return !xhr.status && location.protocol == "file:" ||
                                ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status == 304 || xhr.status == 1223;
                } catch(e){}
                return false;
        },


The main reason is not the http code 204 itself, but it is about what 204 actually means.  HTTP 204 means No Content.  It seems like "No Content" is something not correct at the very first impression, but think about this way, what about people who wants a web service to response a success but they don't need a body or message (well, they just want to know it is a success and that's all).  And that is what HTTP 204 means, success but no content.   

Even though the above jQuery snippets says that 204 is a valid response, and treated it as success;  however, somewhere later, jQuery has this function to throw a "parseerror" when there is no content.

        httpData: function( xhr, type, s ) {
                var ct = xhr.getResponseHeader("content-type"),
                        xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0,
                        data = xml ? xhr.responseXML : xhr.responseText;

                if ( xml && data.documentElement.tagName == "parsererror" )
                        throw "parsererror";
                . . .

So this is what jQuery ( older version ) says, "We accept 204, but if it is no content, we will throw you an error".

In order to fix the issue, you will need to do something in your error() callback

error: function(xhr, errText) {
   if(xhr.status == 204) {
       _successHandler(what, ever);
       return;
   }
   _errorHandler(what, ever);
}

Wednesday, June 29, 2011

Javascript Non Blocking development

Symptoms: You  have a javascript code that blocks your other script or even the UI.  And you are scratching your head now :)

Most of the modern browsers are using a single "thread" or "process" to handle both UI update and javascript execution (mostly update the UI as well).  And think about this "thread" as the browser UI queue, whenever you have javascript needs to be executed, it will be put into the queue along with other UI updates made by the browser.

And when the javascript code execute, everything else (other scripts and even the UI) will be waiting for that to be finished.  And if that piece of javascript code is a long running script, it will make the user experience very slow or the page will even be stalled.

There are several ways to handle this javascript blocking issue, or in the other words, we are using non-blocking javascript development.

  • The easiest one, place your script at the end of the page, before the end of the body tag.  When javascript is downloading and execute, it will halt the browser rendering, and by placing the <script> at the end of the body tag,  it will give users a full look and feel experience when the page loads. Since the <script> is at the end, so it will start downloading and executing after all initial DOM elements are rendered.
  •  Dynamic loading script.  This requires a little bit coding (yay, just a little bit). What you need to do is waiting till the DOM is ready, you create the <script> tag dynamically.  Once the "src" is executed, the browser will start to download the javascript file and execute the stuff.  In this way, the javascript won't block any browser UI, since it will yield the browser UI before download / execute.
  • If you have a very long/tight javascript loops, your loops could block the browser UI updates, or even cause the browser to stop your script.  In this case, you may want to split your loops by using setTimeout() / setInterval() to delay each execution.  In this way, all other browser UI will have a chance to be updated.
  •  Besides setTimeout() / setInterval(), you can make use of the html5 features of the webworkers.   By using webworkers, you are "outsourcing" some heavy processes to individual "webworkers".  The effect of the web-worker is opening a "new thread" for each call.

There are some links I found may help :-


Tuesday, June 14, 2011

jQuery UI dialog - form not post

Symptoms
I applied the jquery-ui dialog, but now when I click on it, the submit input ( or button ) doesn't do a normal form post.

Case Study
For example, for whatever reasons, you have html like this (just for demo purpose only)

<form name="stuff" action="whatever/listener" method="post">
   <div class="myDialog">
         <input type="submit" value="Submit" />
   </div>
</form>

You applied the jquery dialog on that element as the following,

$('.myDialog').dialog({
            height: 'auto',
            modal: true,
            resizable: false,
            draggable: false,
            autoOpen: true,
            width: 'auto'
});

Everything works fine from UI perspective... Oops, but all of a sudden, you find that the form dialog submit button is not posting to the form... What happen??

Reason
Well, first of all, before trying any methods, try to disable that dialog, and see if the form posts without it. If the form posts without the dialog, then you know you can localize the problem.

If you confirm that it is a jquery dialog issues, then I can tell you that the jquery dialog could move your DOM out of its original place, and that's the reason why the form post doesn't work.

Solution
You can move the dialog box content back to the form by doing this
$(".myDialog").parent().appendTo("/html/body/form[0]");

Saturday, June 11, 2011

Latest jQuery plugin - HTML5 Spin Wheel

Just created a new jquery plugin just for fun recently. Part of the algorithms are taken from some other places. What I did here is just playing around with the HTML5 canvas, but somehow I also package that as a jquery plugin.

Here is the demo below:-
Try to enter the things you want to put on the wheel, for example,

  • Where to go to lunch today
  • Who is going to wash dishes today
  • Who is paying for lunch today
  • ... etc

Press Add to add more items.  After adding all your items, you can click the spin.



Note:
Feel free to modify the source as you will.  There is an array of applications that can be based on this plugin.  For example, you can integrate that with Yelp to create where to go to lunch today.  This plugin is just a simple demonstration of what HTML5 is capable of, but HTML5 is far powerful that just that.

IE User Note: 
It is recommended you use the latest (modern) browsers, like Chrome / Firefox / IE9, because HTML5 is still relatively new stuff, older browser may not support those at this point.  There are some libraries that can make your browser to recognize HTML5 tags, in our case of canvas, you can take a look at the Google's ExplorerCanvas.    

Friday, June 10, 2011

Latest RequireJS throws Mismatched anonymous require.def modules

Symptoms
Latest RequireJS throws Mismatched anonymous require.def modules

Here is a list of known situations where this error can occur:

1) You are using the loader plugins or other anonymous modules in your code, but you do not use the RequireJS optimizer to concatenate files. The RequireJS optimizer knows how to name anonymous modules to avoid this error.

2) If you manually code a script tag in HTML to load a script with an anonymous define() call, this error can occur.

3) Also seen if you manually code a script tag in HTML to load a script that has a few named modules, but then try to load an anonymous module that ends up having the same name as one of the named modules in the script loaded by the manually coded script tag.

And if you are upgrading from older versions, you may be still using require.def() function, try to change to use the define() function instead.  And also, for your modules that using define() function, please check if you are using order!,  you probably want to take that out.  In the old version require.def() won't throw error when you use order!, but after I upgrade to the latest version, and it throws error when I include order! in my define() function.  So in my case, it fixed after I took out all the order! from my define() function. I believe the order! is not suppose to go into the define() function, as I didn't see that mention at all in the documentation.

For more information, please read the RequireJS documentations.

Monday, June 6, 2011

Getting nodeName from jQuery

Below method won't work
$('.myClass').nodeName;  // it will return undefined

The reason is you are calling a "property" that is not existing in the jquery object.

...

The correct way to do this is
$('.myClass').get(0).nodeName;

or

$('.myClass')[0].nodeName;


Wednesday, June 1, 2011

How to create your Custom Event in jQuery

If you have used jquery before, I believe you should be very familiar with using events like the following:-

$('.myClass').click(function(e){
    e.preventDefault();
    // doing something here
});

or

$('.myOtherClass').bind('mouseenter', function(e) {
    e.preventDefault();
    // doing something here
});

But do you know that you can create your own Custom Event and call it just like a standard events.

$('.myAnotherClass').bind('SuperClick', function(e) {
    e.preventDefault();
    // doing something here
});

and somewhere in your code, you can call your custom event 'SuperClick' like this

$('.myAnotherClass').trigger('SuperClick');

That's it, you can bind your custom event to your element (object), and next time when you trigger that custom event, your stuff will run. However, don't think too complicated if you are still not sure what's going on... Think of it as if you are just creating a javascript function and you can reuse that function whenever you call it.

But there is a catch when you use this type of custom event, make sure you trigger the custom event using the same element.  The reason is you bound the custom event to an object (element), and only that element can listen to that custom event.  Make sense?

Monday, May 16, 2011

jQuery Plugin ( Recently Published )

I've published several jQuery plugin lately and let's share the links here :)

Simple Auto Complete
http://www.jsclasses.org/package/70-JavaScript-Auto-complete-input-text-from-data-in-the-page.html
This  jQuery plug-in can auto-complete input text from data in the page. It can auto-complete the text entered in text input with text entries by searching in another given elements of the page. The search results can be cached to accelerate future searches.

Basic Slideshow
http://www.jsclasses.org/package/36-JavaScript-jQuery-plugin-to-present-a-slide-show-of-images.html
This object is a jQuery plugin for presenting a slide show of images. It can present a slide show made of images already present in the current Web page within given elements. The slide show image caption text is retrieved from a data attribute of each image. The page element where the slide show images will appear is also configurable. 

Flash Messages 
http://www.jsclasses.org/package/35-JavaScript-Flash-page-elements-a-number-of-times.html
This object is a jQuery plug-in that can be used to Flash page elements a number of times. It can make a given page elements appear and disappear a given number of times. The period of time during which the elements show up if configurable.

Thursday, April 14, 2011

jQuery - check element if it's existed

This is the correct way of doing this

if($('.myClass').length > 0) {
    // blah ...
}

Some people ask, why the following doesn't work??

if($('.myClass')) {
    // blah ...
}

Well, it's because jQuery selector always returns you an Object. 

===

Of course, if you are using plain javascript, then it is correct.  For example,

var home = document.getElementById("home");

if(home) {
  // blah ...
}

Tuesday, April 12, 2011

jQuery selectmenu - call back

The jQuery selectmenu  documentation is kind of confusing, it lacks of examples and documentations.  Well, it covers how to use this plugin in its basic way, but nothing more.

I came across this problem of firing callback when the menu is changed. The documentations says;
Callback events The selectmenu plugin provides callbacks for open, close, select, and change events, allowing you to execute scripting based on those events. The change event even triggers a change event on the original select element, allowing you to reliably track form change events.

Do you pass your call back in as one of your config parameter or what?? And finally it is how it works:

// You first need to initialize the select menu and bind your element
$('.menu-drop').selectmenu({ style: 'dropdown' });

// Now there are some new functions bind to ".menu-drop" that you can use

$('.menu-drop').change(function () {
        //either ajax call or whatever you want
});


Well, of course, you should be able to chain that (recommended) ~

$('.menu-drop').selectmenu({ style: 'dropdown' }).change(function () {
        //either ajax call or whatever you want
});


Friday, April 8, 2011

jQuery nth-child counts wrong in IE ??

I came across an interesting problem today, we are using a nth-child selector in jQuery.

$(".tag_even tr:nth-child(2n)").addClass('even');

Somehow a person code something wrong in the table, he inserted a <div> as one of the <tr>.

Because the selector in jQuery target at "tr", so the div should be ignored.  It make senses, right?

This assumption is true for FF / Chrome and Safari, but IE still count the "div" in? What the hack??

It is because IE wrap the table each children elements with a "nodeIndex", and jQuery when in IE, it uses "nodeIndex" for counting the nodes, no matter it is a "tr" or not.  The below is how jQuery implement the nth-child selector, and please look at the "bold" part that it is using "nodeIndex".


                CHILD: function(elem, match){ 
                // ... 
                        case 'nth': 
                                        var first = match[2], last = match[3]; 
                                        if ( first == 1 && last == 0 ) { 
                                                return true; 
                                        } 
                                        var doneName = match[0], 
                                                parent = elem.parentNode; 
                                        if ( parent && (parent.sizcache !== doneName || ! 
elem.nodeIndex) ) { 
                                                var count = 0; 
                                                for ( node = parent.firstChild; node; node = node.nextSibling ) { 
                                                        if ( node.nodeType === 1 ) { 
                                                                node.nodeIndex = ++count; 
                                                        } 
                                                } 
                                                parent.sizcache = doneName; 
                                        } 
                                        var diff = elem.nodeIndex - last; 
                                        if ( first == 0 ) { 
                                                return diff == 0; 
                                        } else { 
                                                return ( diff % first == 0 && diff / first >= 0 ); 
                                        } 
                        } 
                // ... 
                },