Archive for 'JavaScript'

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.

AJAX and SEO – Is it possible to get them together?

About 7 months ago I threw a question on LinkedIn, AJAX & SEO. It was about is ajax seo friendly! (The website can be found here http://demo.zpbappi.com). Most of the people answered “NO”. All of them suggested me not to use 100% Ajax(ed) website as search endings do not render the javascript. The site has one index.php page and no other pages. When you click any link/buttons it loads the content dynamically using ajax. So I agreed that search engines wont be able to crawl the site properly and stop thinking about it any more.

One week ago I got a project to fully ajaxify a simple static website camillenelson.com with search enginge readability. I already knew (still then) it is not possible. I started re-thinking about the issue and find out a solution of my own. The site has only 8 pages which is a plus point. To assume any site from search spider’s view just disable the javascript from your browser settings and you’ll understand how the spider will go from one link to another.

For example:

<a href="about.html"
onclick="javascript: Load('about'); return false;">
    About
</a>

When javascript is enabled, clicking on About link won’t go to about.html page (return false;), rather it would call Load function. I think you’ve already got the idea!

In real I used jQuery to make the whole thing unobtrusive. The static html pages (already done) except index.html were kept as they are. In index.html the container div (the only div that changes for different pages) loads the content of different pages. I created a folder “ajaxContent” and created the html files with same name of the main html(s) but they contain only the contents, not the full html page.

Here is the jQuery code I used: (N.B. All the links are assigned with “ajax” class.)

$(function() {
    $("a").focus(function() {
        this.blur();
    });
    $("a.ajax").click(function() {
        var lnk = "ajaxContent/" + $(this).attr("href");
        var hover = $(this).find("img").attr("src");
        var img = $(this).find("img");
        $.ajax({
            url: lnk,
            beforeSend: function() {
                $("div#container").html('Loading...');
            },
            success: function(d) {
                $("div#container").html(d);
            },
            complete: function() {
                $("#loading").hide();
            }
        });
        return false;
    });
});

If you have any better idea to make a fully-ajaxed website SEO friendly please let me know.

Thanks

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.

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!

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: