Archive for 'Core JavaScript'

IE6 fix for select box over absolute positioned element

IE6 sux. General css/javascript hover drop-down menu uses a div or ul with position:absolute. No matter how much you increase the value of z-index the select box (windowed element) will always remain on top most – yes only on a special browser, Internet Explorer 6. The reason is IE6 considers select element as windowed element and keeps it always on top layer.

IE6 select box over div

Solution is using iframe on top of select element, as iframe is also a windowed element placing it on top of select box fix the problem.

IE6 select box over div prob fixed using iframe

Here is the typical HTML code for this drop-down menu:

<div class="top-menus" style="left: 221px; top: 127px;">
<iframe frameborder="0" scrolling="no" align="bottom" marginheight="0" marginwidth="0" src="javascript:'';" style="height: 200px;"></iframe>
    <ul>
      <li><a href="#">Bracelets</a></li>
      <li><a href="#">Rings</a></li>
      <li><a href="#">Earrings</a></li>
      <li><a href="#">Necklaces</a></li>
    </ul>
</div>

The inline css is calculated using jQuery offset() function. FYI, you can easily get the width,height,left,top position of any element using jQuery(“element”).offset(). Make sure the width and height of the iframe is exactly same of it’s overlying UL element. If you apply any border to the UL, you have to consider that during calculating the proper width/height of the iframe.

This is the sample jQuery code:

var timer = null; // global
$("#top-nav a").hover(function(){
	clearTimeout(timer);
	$("#top-nav a:not('.cur')").removeClass("selected");
	$(this).addClass("selected");

	var o = $(this).offset();
	var left = o.left + 1; // 1px extra for border
	var top = o.top + 32; // 32px for placing it just below the horizontal menu
	if($(".top-menus").length){
		if(left == $(".top-menus").offset().left)
			return;
		else $(".top-menus").remove();
	}

	$("body").prepend('<div style="left:'+left+'px;top:'+top+'px;" class="top-menus"><iframe src="javascript:\'\';" marginwidth="0" marginheight="0" align="bottom" scrolling="no" frameborder="0"></iframe><ul>'+html+'</ul></div>');
		$(".top-menus").find(".parent, .child").remove();
		var hi = $(".top-menus").find("ul").height();
		$("iframe").height(hi + 2); // extra 2px for border

}, function(){
	clearTimeout(timer);
	timer = setTimeout(function(){$("body").find("iframe,.top-menus").remove(); $("#top-nav a:not('.cur')").removeClass("selected");},300);
});

$(".top-menus").live("mouseover",function(){
	clearTimeout(timer);
}).live("mouseout",function(){
	clearTimeout(timer);
	timer = setTimeout(function(){$("body").find("iframe,.top-menus").remove(); $("#top-nav a:not('.cur')").removeClass("selected");},300);
});

I know this code won’t exactly fulfill your requirement, you can get the main idea from this and write your own code yourself. You can see it in action on www.trendtogo.com.

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.

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.

How to get currently logged on windows username in PHP and Javascript

It is very simple to get the current windows username in PHP. The following one line of code will output the username of the system where the server is running. If you are running this from localhost then your system login name will be shown. But you can not get the visitor’s system login username.

<?php echo getenv("username"); ?>

By using javascript (actually VBscript) you can get the visitor’s windows username. But there are also limitations. It only works on IE.

<script language="VBscript">
Dim X
set X = createobject("WSCRIPT.Network")
dim U
U=x.UserName
MsgBox "username: " & U
</script>
<script language="Javascript">
var a = U;
alert("Hello, " + a.toString());
</script>

This code will show you the current windows username. But won’t work if run from http://. Open the page from your computer with IE and it’ll work, otherwise not.

Actually it is not possible to get the windows username of your website visitors as it is a security issue. So don’t waste your time if you are trying to do that.

Flickr Uploader Clone: Free Download with source code

I have been searching for flickr uploader clone script online for one of my project. But no luck! There is no such thing on internet. Then I started with analyzing the javascript code of flickr uploader. Lucky that they did not packed their js. Though it was minified by removing white spaces. I used an online javascript code beautifier to make it pretty readable. After that the challenging part began. Cos, the code normally does not work on my local server. After huge hard working of long one week I made it finally. It works great! Even it works for videos too. You can modify the code for uploading any types of file. FYI, Flickr has used YUI (Yahoo User Interface) library for their uploader. So there is no licensing problem if you use this uploader for your own.

For my own need I added 2 extra fields. They are sent to server via POST method along with the FILES. One thing I’ve noticed, it can upload file faster than normal file uploading method. Cos, the file is encoded first via the flash uploader and somehow it is faster than normal.

Upload Multiple File Once

And the great advantage is you can select multiple files during browsing by pressing Ctlr + A or select your files by dragging mouse. By using html <input type=”file” /> you can only select one file at a time which is really so boaring and life-taking when you want to upload hundreds of images.

Flickr YUI Uploader

Here is the online demo. The files are not being saved on my server for my own security!

Download it here completely free in a single zip file!

Modify the index_files/config.js file line no 49,
var _site_root = ‘your script location’;

It won’t work for you until you change _site_root

I have no problem if you use it for your own use. But I do not actually want anyone to put the files/zip on their own site to drive the traffics away from our blog.

If you need any support for modifying or setting it up or any bug report please contact me directly at adnan.eee@gmail.com

Thanks
Have a pain-less uploading experience!

Javascript timer – advanced features, simple to use

javascript is the core of rich UI development and ajax driven website. i enjoy doing these. but in many cases, i thought things would be easier if the setTimeout(…) or setInterval(…) functions were simpler to handle. if you ever tried to make something like fadeout effect or accordion or anything that happens with a certain interval, you may understand what i mean. so, i thought it would be great to use a timer if anyone made already. i searched, got hundreds. but, none of them seemed perfect for me to use everywhere. for example, if you are familiar with visual basic (former) or .NET timer object, its very easy to use anywhere, anyhow. actually, this was the basic idea for my development (though it supports more than the basic).

so, i wrote a javascript timer object trying to provide a complete object oriented solution (basically for me, but you can use it too :). its very simple to use, yet very powerful. you can set your desired interval and a callback function which will be called after each interval.

the simplest use would be:

var timer = new Timer(1000, myfunction);
timer.start();

first parameter sets the interval in milliseconds and second is the callback function to call. so, this will call myfunction() every second.

methods of Timer object and their parameters and return values (API reference) can be found here.

but, dont you want something more? well, in that case, first of all you should know that Timer object supports concatenation for almost every function. so you can rewrite the above code as:

var timer = new Timer(1000, myfunction).start();

whenever you want to stop the timer, just call:

timer.stop();

isn’t that simple? well, that’s just the beginning.

its time you are introduced to some necessary functions:

//pauses the timer
timer.pause();

//resumes the timer, if it was paused
timer.resume();

you should keep in mind that, there is a difference between stop() and pause(). when you pause the timer, it remembers how much of its interval is left. after resuming, it runs the remaining time of its interval. for example, if you set interval to 2000 milliseconds and pause the timer after running 1500 milliseconds; when you resume, it will call the callback function (i.e., myfunction ) after 500 milliseconds. this feature could be useful for rotating ads of news flashers in a website.

also, you have various functions like interval, addCallback, and many more. so, our very first code can be rewritten as:

var timer = new Timer().interval(1000).addCallback(myfunction).start();

or, to please eyes:

var timer = new Timer();
timer.interval(1000)
.addCallback(myfunction)
.start();

note that, Timer class also supports empty constructor like Timer() which is my personal favorite.

wait.. where is the multiple callback feature? well here it is:

var timer = new Timer();
timer.interval(1000)
.addCallback(myfunction1)
.addCallback(myfunction2)
//......
.addCallback(myfunctionN)
.start();

okay? well, you should know that functions are executed in parallel. if you dont trust me, try this:

var timer = new Timer();
timer.interval(1000)
.addCallback( function() { alert('hi there.'); } )
.addCallback(myfunction)
.start();

see, alert doesn’t block executing myfunction. i tried adding 20 callback functions. some of them showed time in a div, and some did something else. all of them executed in parallel. i.e., none block others’ execution.

well, so far everything runs forever unless you call timer.stop() or timer.pause(). what if you want the basic setTimeout(…) function back? there’s a way:

var timer = new Timer();
timer.interval(1000)
.addCallback(myfunction1)
.addCallback(myfunction2)
.runOnce(true)
.start();

this works same as setTimeout(…), i.e., executes myfunction1() and myfunction2() simultaneously one time after the specified interval. plus, you have the ability to stop or pause it anytime. is that sufficient for you? well, there’s more.

imagine, you are building an ajax driven webmail interface (for example, consider gmail). you have a clock showing current time in user’s inbox. also, you want to check if there is internet connection available in every 3 seconds. and you want to check for new mails in every 10 seconds. you may want more, but i will show you a skeleton program of these three feature using Timer object. your code should be something like this:

function update_clock(){
//code to update the clock
}

function check_connection(){
//code to check if there is connectivity with your server
//a simple XMLHttp request may be.
}

function check_mail(){
//an XMLHttp request to check for new mails
}

var timer = new Timer();
timer.interval(1000)
.addCallback(update_clock)
.addCallback(check_connection, 3)
.addCallback(check_mail, 10)
.start();

isn’t that too easy for that complex task? notice the second parameter in addCallback method. think like, the Timer object generates a pulse at given interval. the second parameter of addCallback method tells Timer object that this callback method should be executed at every Nth pulse; where N=1, 2, 3, … (here, N=3, 10). the seconds parameter, N, is optional and default value is 1.

now, off the record, someone asked me, if it can trigger a callback function (say, check_connection function from the example above) in 1.5 second interval!!! whoever is thinking to pass 1.5 (that is the quickest solution, i guess) as the second parameter, please dont. it only accepts integer number. but, there’s a work around. you need to learn some elementary math and come back here. then you will come-up with a solution like this:

var timer = new Timer();
timer.interval(500)
.addCallback(update_clock, 2)    //500 * 2 = 1000
.addCallback(check_connection, 3)    //500 * 1.5 * 2 = 1500
.addCallback(check_mail, 20)    //500 * 10 * 2 = 10000
.start();

thats a good solution and this is what i had in mind ;). wait, one question is still hanging.

what will happen if i add .runOnce(true) just above .start() in the example above?

well, what is desired? i think, each callback function should be executed exactly once. thats what i implemented. so, regardless of continuous pulses provided by Timer object, update_clock() will execute exactly once after 1 sec, check_connection() will execute once after 1.5 sec and check_mail() will execute once after 10 sec. then the timer will stop. any suggestion?

well, there are still few more functions left to mention. but, they are too easy to explain. see API Reference for description/usage of functions of Timer object.

lastly be sure to have a good asp.net web hosting provider, it can make all the difference. for any suggestion, bug report or query, please leave a comment. hope you like it.

Links: