Tag Archives: jQuery

IE6 png alpha transparency fix for dynamically loaded images via ajax

IE6 is always a nightmare for web developers. The most painful drawback is it does not support the alpha transparency of transparent png images and you know how to solve this problem using iepngfix or jquery.pngFix.js.

You must be thinking.. what is new in my post then!! Have you ever used any of them for dynamic png images? Some people call it “Loading an image via ajax”. Let me explain what I mean by “dynamic png images”.. say you have a page where clicking on a link does not reload the page, but load a transparent/semitransparent png image. Most specifically, I was working on a project where user types some text in a text box, it is converted to transparent png image on the fly using php and then it is displayed inside a div which has a graph-paper like background-image. This whole thing is done without reloading the page at all.

It looks okay on FF, safari, IE7 but on IE6 the transparent portion looks Grey. The iepngfix.htc script didn’t help, cos it only works on the images which are loaded and showed at the beginning of page loading. After the page is fully loaded and you load another png image using ajax this script won’t work. But I could not do that for my project as it is meant to be loaded dynamically using ajax for the sake of advanced user experience.

I started googling for it, no luck. Finally I modified a portion of code used in the iepngfix.htc file and fixed the problem using this simple javascript code. (FYI, I was using YUI so only the browser checking part is done using it, you can use jQuery or pure javascript for browser detection)

var textImage = new Image();
textImage.src = "text.png"; // src of the png image. okay if not ie6
if (YAHOO.env.ua.ie > 5 && YAHOO.env.ua.ie < 7) { // if IE 5+ or 6 or 6+
    var timg_src = textImage.src;  // textImage
    var new_img = new Image();  // just as a preloader
    new_img.src = timg_src;

    new_img.onload = function(){ // remember, the image is being loaded dynamically, so apply the filter after it is loaded.
        var ti = document.getElementById("textImage"); // the ID of the img tag where it'll be loaded
        ti.style.width = new_img.width; // you can get the width/height of image after it is fully loaded
        ti.style.height = new_img.height; // and you must "DEFINE" the image height/width. "auto" height/width won't work!

        // This is it. apply the filter :)
        ti.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + timg_src + "', sizingMethod='scale')";
        ti.setAttribute('src', 'blank.gif'); // don't forget this part. the image src is replaced with a blank gif image.
    }
}

Here is another version of the code which is not for dynamic images. It’s alternative of iepngfix.htc. In some cases you may not like using iepngfix.htc, rather want to control it yourself. For example if your page has hundreds of png images which are not transparent and only a few images that are transparent, in this case using iepngfix.htc will make the whole process too slow. I applied a pseudo class “png” to all png images & divs with png background image with fixed height & width and applied this simple jQuery code:

$(window).load(function(){ // after all the images are loaded
    if ($.browser.msie && parseInt($.browser.version.substr(0, 1)) < 7) { // ie6 or 5
        $("img.png").each(function(){
            $(this).css("filter", "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + $(this).attr('src') + "', sizingMethod='scale')").attr("src", "images/blank.gif");
        });
        $("div.png").each(function(){
            var bg = $(this).css("backgroundImage");
            bg.match(/^url[("']+(.*\.png)[)"']+$/i);
            bg = RegExp.$1;
            $(this).css("filter", "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + bg + "', sizingMethod='crop')").css("backgroundImage", "none");
        });
    }
});

Hope you’ll find it helpful. Please let me know if you have any better idea.

Using Dreamweaver Spry validation with jQuery ajax form plugin

Writing form validation code manually is a boring task. Not only that, editing or adding new fields each time and modifying the validation code accordingly is such a pain. When Dreamweaver added the Spry form validation with CS3 the nightmare is over. The greatest feature of using it is you can do the form validation work automatically with a couple of mouse clicks and no hand written code! And you can easily change/edit or add/remove the fields.

I know jQuery has simple validation plugin but you have to write the codes for it, which is time consuming. I always use the spry validation of dreamweaver as I learned using it for it’s simplicity. When I tried to use it with the jQuery ajax form submit plugin I got disappointed. It didn’t work! I didn’t stop trying. And finally I found the way which I’m gonna share with you :)

Here is the simple code that you need in the “beforeSubmit” parameter of $.ajaxForm

$("#formID").ajaxForm({
    url: "submit.php",
    beforeSubmit: function(formData, jqForm, options){
        if (Spry) { // checks if Spry is used in your page
            var r = Spry.Widget.Form.validate(jqForm[0]); // validates the form
            if (!r)
                return r;
        }
    },
    success: successFunction,
    complete: completeFunction
});

Hope that’ll help a lot boosting your web development.

Gmail uploader clone with drag drop feature : Free Download with source code

Recently I developed the gmail file uploader clone using jQuery. Here is the online demo.

Gmail uploader clone with drag drop feature screen shot

I added some extra functionalists.
You can see the image thumbnails after the uploading is completed. There is a cross button at top right of each thumbnail, clicking on it will delete the image. If you right click on the image you’ll see a context menu from which you can delete the image too along with replace the existing image option.

The most interesting feature is you can drag drop the thumbnails to change the order. Yes this is essential when you need to maintain the order of images in classified sites after uploading them, also a little modification will let you edit the image order later time by dragging the thumbnails. The image name and the image title is dynamically added in the “updateInfo” form and send(post) via the hidden fields imgs[] and imgComment[]  array. You can easily get the order by php using foreach loop on $_POST['imgs'] field. Just hit the submit button after uploading 2 images and you will see the output on post.php page. (hope that makes sense).

Download it for free in a single zip file

If you have any better example of gmail uploader clone please share the links in comments.

jQuery vs. prototype.js

I’m basically a jQuery developer. I had little knowledge about prototype.js. All I knew is jQuery is better than prototype, so I never got interested about it.

However, for some reason I started a project with prototype.js and each line of code makes it clearer that which one is better. Somehow I finished the project using prototype.js along with scriptaculous.js and effects.js. Everything was fine in IE7 and FF 3. But it breaks in IE6. I was not happy with the unnecessary huge code. For example there is no live event in prototype.js, you can not apply an event to a group of elements with same class (You have to use loop for it), there is nothing like jQuery.animate function by which you can do any css animation (You have to add scriptaculous.js for some pre-built animation effects!) and a lot more limitations.

Even the scriptaculous.js is not that rich, for example using ScrollTo effect you can smoothly scroll to any anchor tag “vertically” only but no way of ScrollTo horizontally(!) in case your page is landscape orianted. Here is the code that I used instead(I found the idea from the source code of ScrollTo function):

var scrollOffsets = document.viewport.getScrollOffsets();
var elementOffsets = $$('div.active ul li')[index].cumulativeOffset();
new Effect.Tween(null,scrollOffsets.left,elementOffsets[0] - lo,function(p){window.scrollTo(p,scrollOffsets.top);});

The equivalend jQuery code is:

$("html,body").animate({
scrollLeft: ($('div.active ul li').eq(index).offset().left - leftOffset) + 'px'
}, "slow", "swing");

There are a lot more examples like this. The summary is the code using prototype.js was 180 lines and the equivalent code using jQuery is now only 160 lines + a lot of mental relief that it would work on all browsers :)

One thing I want to make clear is I have no intention to boost anything. In fact both of them are free.

jQuery “live” event

jQuery 1.3 has a brand new and powerful event. It was very painful and a nightmare to maintain events for newly created elements. For example if you define “click” event for existing elements at domready it won’t work for dynamically added elements later. Each time a new element is added you had to bind the event to that element. Which results in many recursive function calls, for huge applications so tough to maintain the events dynamically and finally not efficient coding structure.

The new “live” event has made our life easier to a great extent!

For example:

$("a").bind("click", function(){$(this).blur();});

  This simple code will remove the unwanted selection for your EXISTING “a” tags only. But if any new “a” tag is added dynamically to the dom, you have to do the same thing again. But if you use

$("a").live("click", function(){$(this).blur();});

  this will remove your headache about new “a” tags which will be added later.
So live event will reduce the load of calling same function(for applying same event) again and again for new elements. To unbind live event you have to use “die”.

One very important point to note – live event only works for direct selectores. For example, this would work:

$("li a").live(...)

but this would not:

$("a", someElement).live(...)

and neither would this:

$("a").parent().live(...)

I must say jQuery is like a “Lamp of Aladdin” for web developers which has made javascript application development a fun. And the new live event will boost up that fun and make more time for dating ;)

Documentation: http://docs.jquery.com/Events/live

A better process to find maximum z-index within a page

Once I needed to get maximum z-index of a DIV to show message at the top of the screen.
Usually, I used arbitrary z-index of 100 of the DIV. But that one is not at the top and it’s hidden by others.
What’s wrong? And unfortunately I found that there are 3 more div-s which have z-index attribute which are greater than 100.
So I changed the z-index to 1000. This time I can see one portion of the DIV.
But 2 more elements get the desired message container DIV overlaid. Frustrating! Huh!
Trial and error method always makes you delay.
I know JavaScript or jQuery may get rid of this hell.
I made an absolute tinny code to find the highest z-index of absolute DIV
to show my shouting box and to make it appear absolutely at the top of all html elements.

//include jQuery.js --  visit: http://jquery.com/
$(function(){
    var maxZ = Math.max.apply(null,$.map($('body > *'), function(e,n){
           if($(e).css('position')=='absolute')
                return parseInt($(e).css('z-index'))||1 ;
           })
    );
    alert(maxZ);
});

I used selector of ”body > *‘ instead of ‘body *‘.

body > *‘ means all tags/elements which are found at first depth of
whether ”body *‘ selects all tags/elements at any depth.
It doesn’t matter what’s is the maximum/highest z-index of an absolute element
rather it matters what’s the maximum/highest z-index of the absolute elements
which are next to in first depth only to show the shouting box on top most strata.

N.B. Shouting box is appended to document.body in this case.

jQuery Manual in .chm format (Update: version 1.4.2)

The online version of jQuery documentation is really great. But they do not provide any offline version of their docs. I’ve got the jQuery docs in a single .chm file. Hope this will help you a lot.

Download jQuery Manual (.chm)

Update: jQAPI offline version Documentation for the road.

Download HTML Version. Documentation for jQuery version 1.4.2 – 1.6MB – 03/20/10
Download AIR Version. Documentation for jQuery version 1.4.2 – 1.6MB – 03/20/10

I recommend the .air version, it’s cool!