rss

jQuery Custom Alertbox Plugin

Category : Javascript

I was working on an app using Adobe AIR platform. At one stage i was at a point where i needed an alert system that i can customize according to my needs. I searched for some of the plugins that were very good but accidently i bumped into a link where it talks about how to create a jQuery plugin, so i thought of creating my own which i can customize according to my needs.
I am providing the code here so that you can use this code and customize it according to your need.

?View Code SCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//PLUGIN FOR THE NEW ALERT BOX
 (function($){  
	 $.fn.extend({   
		 customAlert: function(options) {
			var htmlStr = '<div id="amitOverlay"></div><div id="alertMsgDiv"><div id="aClose">[X]</div><div id="aMessage"></div></div>';
			var defaults = {   
				 bgColor: '#000',  
				 opacity: '0.6',  
				 message: 'This is a test message from the plugin',  
			 };  
 
			var options = $.extend(defaults, options);  
			$("body").append(htmlStr);
			$("#alertMsgDiv").css({'display': 'block', 'width': '100px'});
			$("#amitOverlay").css({'display': 'block', 'top': '0px', 'left': '0px', 'width': $(this).width() + "px", 'height': $(this).height() + "px", 'background-color': options.bgColor, 'opacity': options.opacity});	
 
			$("#aMessage").html(options.message);
			$("#alertMsgDiv").animate({width: 300}, 300);
 
			$("#amitOverlay, #aClose").click(function(){	
				$("#alertMsgDiv").remove();
				$("#amitOverlay").remove();									
			});
		 }  
	 });  
 })(jQuery);
 
 
/*
 USAGE
 $(document).ready(function(){
	$(document).customAlert({opacity:0.4, bgColor: "#aaa",  message: 'This is a test message' });
 });
 */
Download the code here
  • Share/Bookmark

QUnit:JavaScript Testing Framework

Category : Javascript

QUnit is a powerful JavaScript unit testing framework that helps you to debug code. It’s written by members of the jQuery team, and is the official test suite for jQuery. But QUnit is general enough to test any regular JavaScript code, and it’s even able to test server-side JavaScript via some JavaScript engine like Rhino or V8.

If you’re unfamiliar with the idea of “unit testing”, don’t worry. It’s not too difficult to understand:

In computer programming, unit testing is a software verification and validation method in which a programmer tests if individual units of source code are fit for use. A unit is the smallest testable part of an application. In procedural programming a unit may be an individual function or procedure.

This is quoted from Wikipedia. Simply put, you write tests for each functionality of your code, and if all of these tests are passed, you can be sure that the code will be bug-free (mostly, depends on how thorough your tests are).

  • Share/Bookmark

Using JQuery & Prototype together

Category : Javascript

You would surely have used JQuery and Prototype for dynamic web applications like Lightview, Prototip, etc. Here i would show you how to user them two together, on the same page.

Problem
The Problem JQuery uses a “$” as a shortcut for “jQuery” and Prototype uses “$” as well. We can’t have JQuery and Prototype using the same “$” namespace.

The Fix
Thankfully JQuery has a neat little function called jQuery.noConflict( ) which you basically just need to stick at the top of your JQuery file and replace the “$” alias with “jQuery” for each function. Example:

jQuery.noConflict();
// Do something with jQuery
jQuery(“div p”).hide();
// Do something with another library’s $()
$(“content”).style.display = ‘none’;

Of course, there are other ways of solving this issue with jQuery.noConflict( )

NOTE: JQuery doesn’t get along with MooTools and YUI very well either, luckily this can also be solved with the jQuery.noConflict( ) trick.

  • Share/Bookmark

Parse JSON with jQuery and JavaScript

4

Category : Javascript

Believe me that the javascript libraries available for user have helped speed up the work to great extent, and they are browser independent.

Every time i wrote a javascript code i have to check whether its working on different browsers or not, but thses libraries came and saved me from doing all those difficult work.

Here i had a requirement of parsing a JSON with jQuery for my project, i had no idea whatsoever about doing this, but ultimately this article saved me, i really thank him for the code. Here i will tell you people how to do that.

Here is the JSON object that we will be parsing.

?View Code SCRIPT
1
2
3
4
5
6
7
8
9
10
11
{attributes:[{title: "Project Delivered", post_id: 31, post_type_id: 5, parent_post_id: null, description: "Working", time_zone: "International Date Line West", user_id: 4, image_path: "http://localhost:3000/user/image_path/4/thumb/3.jpg", user_name: "TestUser1", created_at: "Thu Mar 27 04:29:33 UTC 2008", email: "testuser1@testurl.com"},{title: "Task Response", post_id: 45, post_type_id: 6, parent_post_id: null, description: "completed", time_zone: "International Date Line West", user_id: 3, image_path: "http://localhost:3000/user/image_path/3/thumb/2.jpg", user_name: "TestUser2", created_at: "Fri Mar 28 06:13:49 UTC 2008", email: "testuser2@testurl.com"},{title: "abhijats post", post_id: 58, post_type_id: 1, parent_post_id: 55, description: "", time_zone: "International Date Line West", user_id: 2, image_path: "http://localhost:3000/user/image_path/2/thumb/9.jpg", user_name: "TestUser3", created_at: "Fri Mar 28 11:37:16 UTC 2008", email: "testuser3@testurl.com"},{title: "Give demo", post_id: 41, post_type_id: 4, parent_post_id: null, description: "\074strong\076Give demo\074/strong\076", time_zone: "Paris", user_id: 1, image_path: "http://localhost:3000/user/image_path/1/thumb/mazewallpaperv2.jpg", user_name: "TestUser4", created_at: "Fri Mar 28 06:04:02 UTC 2008", email: "testuser4@testurl.com"},{title: "Status Update", post_id: 37, post_type_id: 5, parent_post_id: null, description: "Working", time_zone: "Paris", user_id: 1, image_path: "http://localhost:3000/user/image_path/1/thumb/mazewallpaperv2.jpg", user_name: "TestUser4", created_at: "Fri Mar 28 05:20:37 UTC 2008", email: "testuser4@testurl.com"},
 
{title: "abhijat has read acess", post_id: 57, post_type_id: 1, parent_post_id: 55, description: "", time_zone: "Paris", user_id: 1, image_path: "http://localhost:3000/user/image_path/1/thumb/mazewallpaperv2.jpg", user_name: "AbhilashKumar", created_at: "Fri Mar 28 11:16:50 UTC 2008", email: "testuser4@testurl.com"},
 
{title: "Inxero", post_id: 48, post_type_id: 2, parent_post_id: null, description: "Inxero", time_zone: "Paris", user_id: 1, image_path: "http://localhost:3000/user/image_path/1/thumb/mazewallpaperv2.jpg", user_name: "TestUser4", created_at: "Fri Mar 28 06:56:28 UTC 2008", email: "testuser4@testurl.com"},
 
{title: "New public porjet", post_id: 50, post_type_id: 2, parent_post_id: null, description: "", time_zone: "Paris", user_id: 1, image_path: "http://localhost:3000/user/image_path/1/thumb/mazewallpaperv2.jpg", user_name: "TestUser4", created_at: "Fri Mar 28 10:30:04 UTC 2008", email: "testuser4@testurl.com"},
 
{title: "Status Update", post_id: 35, post_type_id: 5, parent_post_id: null, description: "Hey the stuff is coming good", time_zone: "Paris", user_id: 1, image_path: "http://localhost:3000/user/image_path/1/thumb/mazewallpaperv2.jpg", user_name: "TestUser4", created_at: "Fri Mar 28 01:50:48 UTC 2008", email: "testuser4@testurl.com"},
 
{title: "Status Update", post_id: 36, post_type_id: 5, parent_post_id: null, description: "kljklkl", time_zone: "Paris", user_id: 1, image_path: "http://localhost:3000/user/image_path/1/thumb/mazewallpaperv2.jpg", user_name: "TestUser4", created_at: "Fri Mar 28 01:59:08 UTC 2008", email: "testuser4@testurl.com"}]}

Here is the JSON parser that will parse the JSON object.
this parser uses $.getJSON()
method, with a call to the JSON object file, and a function to pass the data through for parsing.The common $.each() method in jQuery can be used to traverse the “nodes” (keys) that you indicate.

?View Code SCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
$(function(url) {
	$.getJSON("jsonObj.js", function(json) {
 
		/* Parse JSON objects */
		jJSON["title"] = (function() {
			response = {
				values: [],
				count: 0
			};
			$.each(json.attributes,function(i,item) {
				if (item.title != "undefined" &amp;&amp; item.title != "") {
					response.count++;
					response.values[i] = item.title;
				}
			});
			return response;
		})();
 
		jJSON["email"] = (function() {
			response = {
				values: [],
				count: 0
			};
			$.each(json.attributes,function(i,item) {
				if (item.email != "undefined") {
					response.count++;
					response.values[i] = item.email;
				}
			});
			return response;
		})();
 
		jJSON["created_at"] = (function() {
			response = {
				values: [],
				count: 0
			};
			$.each(json.attributes,function(i,item) {
				if (item.created_at != "undefined") {
					response.count++;
					response.values[i] = item.created_at;
				}
			});
			return response;
		})();
 
		jJSON["image_path"] = (function() {
			response = {
				values: [],
				count: 0
			};
			$.each(json.attributes,function(i,item) {
				if (item.image_path != "undefined") {
					response.count++;
					response.values[i] = item.image_path;
				}
			});
			return response;
		})();
 
		jJSON["project_name"] = (function() {
			response = {
				values: [],
				count: 0
			};
			$.each(json.attributes,function(i,item) {
				if (item.image_path != "undefined") {
					response.count++;
					response.values[i] = item.project_name;
				}
			});
			return response;
		})();
 
		/* Function to show data sreams */
 
		displaySocialStream = function() {
			var displayDiv = $('#post_wrapper');
			var dumpP;
			var str = '';
			for(strmCntr =0; strmCntr < (jJSON["title"]["values"].length - 1); strmCntr++){
				if(strmCntr/2 == 0)
				{
					postClass = "post";
				}else{
					postClass = "post alternate-post";
				}
 
				str = str + '<div class="' + postClass + '"><div class="avatar"><img src="' + jJSON["image_path"]["values"][strmCntr]  + '" class="avatar-image"/></div><div class="post-content"><b>Created At:</b> ' + jJSON["created_at"]["values"][strmCntr] + '<br /> <b>Project Name:</b>' + jJSON["project_name"]["values"][strmCntr]  + '<br /> <b>Post Title:</b> ' + jJSON["title"]["values"][strmCntr]  + '<br /> <b>Email:</b> <a href="mailto:' + jJSON["email"]["values"][strmCntr]  + '">' + jJSON["email"]["values"][strmCntr]  + '</a></div></div>';
			}
			displayDiv.prepend(str);
		};
		displaySocialStream();
 
	});
}
)

At first glance it seems I could have refined each reference to a self-invoking function into a single function call. However, you must consider that grabbing data from XML is quite different than grabbing data from JSON. While there is still a parent/child relationship, a child in JSON could be a different type, like an array. There might be several arrays throughout the structure. Simply using the dot operator becomes impossible, and getting different keys can be a unique process.

Each key in jJSON references another hash object with two keys, called values and count. Accessing values will return an array of values, and count will tell you how many of that particular reference exists. For example, how many “title”or “email” key references were obtained from the JSON.

?View Code SCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var jJSON = {
    getValues: function(obj,num) {
        return jJSON[obj]["values"].slice(0,((num == null) ? jJSON[obj]["values"].length : num));
    },
    getCount: function(obj) {
        return jJSON[obj]["count"];
    },
    getRandomValues: function(obj,num) {
        var a = [];
        var b = jJSON[obj]["values"];
        var c = b.length;
        if (num != null && num &lt; c) {
            c = num;
        }
        for (i = 0; i < c; i++) {
            var e = Math.floor(Math.random() * b.length);
            a[i] = b[e];
            b.splice(e,1);
        }
        return a;
    }
};

Along with the key references added to the jJSON object, there are three helper methods. The getValues method will return a number of values for a given object key as an array. If you pass in null as the second parameter, you will receive all values. The getCount method will return a count for a given object key. Finally, the getRandomValues will return a number of randomized values for a given object key.

  • Share/Bookmark

Amit Yadav is Digg proof thanks to caching by WP Super Cache