Posts tagged JQuery

Picture-121-300x157

jQuery Livebuttons Plugin

4

Introduction

I normally develop CMS (control management systems) based on a heavy use of AJAX, and I normally endup writing tones of jQuery functions for different IDs and/or CLASSes. Thinking to create a library that will free me to create the same functions again and again and for different classes I thought about this simple plugin. The reason was that if I was to create a new CMS for my beloved Yii framework, I just wanted to have a system where, by setting some meta data into the HTML elements, the client script will smartly know what to do. I didn’t want to necessary worry about different classes on  my client scripts, I wanted to be just one class.

The idea behind goes a bit further and has something to do with Yii, I want to create extensions that will take care of the correct rendering of a button without having to worry about the client scripts **and** also the same extension could actually call jquery commands easily. I emphasized **and** because Yii already provides an ajaxLink and an ajaxButton but they are not listened to perform client jquery executions and that, as seen in its forums, is causing problems to PHP programmers a lot of times.

Also, I envision an environment where through this, Yii extension designers will be able to create CMS styles, completely different that the one coming from Yii, so Yii users could easily integrate a new layout without even tweaking CSS, or Themes, or Layouts, just their views and by integrating some specialized widgets API, user will be able to program a gallery (for example) with just one line of code on their views. Enough talking, here is the plugin for you to test it and tell me what do you think.

How to use

Include jquery and jquery.livebuttons.js on your document’s head and start monitoring for livebuttons like this:

//
// .selector is the class name the HTML elements have
$('.selector').livebuttons();
$('.selector').livebuttons( options );
//
// we can have more than one
$('.otherselector').livebuttons( otheroptions );

Options

useFirebug

A useful property for debuggin processes. If set to true all logs will be displayed on firebug console (or chrome).

var options = {
    useFirebug: true
}
$('.selector').livebuttons( options );

events

An array of options where to specify the events to monitor. In future releases, we will be able to specify which methods correspond for certain events.

var options = {
    events: ['click','mouseover'] // not a good practice though *yet*
}
$('.selector').livebuttons( options );

methods

This is the most interesting part of the plugin. We could implement our own javascript methods to be used with livebuttons. All methods will receive a ‘command’ parameter, which is actually the object in the meta-data of the HTML element (see below on the examples provided for default methods).

var options = {
    methods: {
        alert: function( command ) {
              alert( command.message );
        }
   }
}
$('.selector').livebuttons( options );

When designing our own javascript functions to be attached to the plugin, we can access internal parser functions with this keyboard. All functions receive a command object and also a reference to the options object. This object have a reference to the parser it self and we could easily access parser’s functions by using this.parser.

The Parser

If you look at the code inside the plugin, you will see that the parser has a couple of good methods to use:

stringify

Converts an object to its JSON representation string

createIFrame

Creates an iframe to be used with FORMs with multipart/form-data. So you can easily send files to the server without the need of reloading the page. Check at its code to see its

removeIFrame

Removes the iFrame previously created with parser.createIFrame() method.

parseJSON

Parses a JSON string and converts it into an object. I know jQuery comes with one, but it throws an error when you include a function into a command object’s property.

Default Methods

You have a couple of methods that already come with the plugin. You can easily override them if required. Here they are:

ajax

Its name is self-explanatory. It receives a command object on the following format:

{method:'ajax',url:'',data:{},success:function(){},error:function(){}}

Example of live button markup

<a class="livebutton" href="#"
data-cmd='{"method":"ajax","url":'http://localhost/',"success":handleAJAX}">test ajax</a>

getscript

Its calling jQuery’s getScript method. It receives a command object on the following format:

{method:'getscript',url:''}

Example of live button markup

<a href="#" class="livebutton"
   data-cmd='{method:"getscript",url:'http://localhost/script.js'}' >test getscript</a>

jquery

Its calling any jQuery’s method. It receives a command object on the following format:

{"method":"jquery","jqmethod": "","target":"","arguments":["url",function(){}]}

Example of live button markup

<a class="livebutton" href="#" data-cmd="{"method":"jquery","jqmethod":"load","target":"#layer","arguments":["url":"http://localhost"]">test load jquery function</a>

Remarks

As previously said, all functions also receive the command object extracted from the HTML element, but that’s not all. The parser automatically includes a jquery reference of the HTML element to the command’s element property.

var options = {
    methods: {
        alert: function( command ) {
              alert( command.message );
             // do not use $( command.element ) as it would like $( $( element ) )
              command.element.attr('title','I have already been clicked');
        }
   }
}
$('.selector').livebuttons( options );

Demo

For the sake of having a demo (I will build a better one) the following script will create a live button that can perform jquery ‘append’ commands. Please note that when you load new content via AJAX on a page that has the livebuttons plugin that you have successfuly initiated, the plugin will also listen to the specified events to those livebuttons loaded via AJAX.

<html>
<head>
<script src="path\to\jquery.livebuttons.js"></script>
<script>
$('.testbuttons').livebuttons();
<body>
<a href="#" class="testbuttons"
  data-cmd="{"method":"jquery","jqmethod":"append","target":"#container","arguments":["new content<br>"]}">Test append</a>
<div id="container"></div>
</body>
</html>

Download

I seriously would like to know what do you think about this system as, again, I am planning to develop extensions for Yii that will embrace it in order to easy the tasks of PHP programmers with client Javascript. I do use this system to create a new system for a personal project and it is working quite good; but I won’t dare to create Yii extensions if you think that what I envision is wrong.

If the below link doesn’t work (it happens normally because you are not registered), please use the following link to download: jquery.livebuttons.js.

http://www.ramirezcobos.com/wp-content/plugins/downloads-manager/img/icons/default.gif download: JQuery Livebuttons Plugin (15.33KB)
added: 15/12/2010
clicks: 166



Tweet this!Tweet this!
Yii Framework

jqPrettyPhoto Extension for Yii

9

I am currently developing a site for a real estate business and it is all built with Yii Framework -I am alone here so I need the best allies for this job :) . During this development I come up with the creation of some cool extensions that I am, of couse, going to share with all of you.

Introducing jqPrettyPhoto

This extension is making use of the grrrreat jQuery plugin called PrettyPhoto. Here is its description in detail:

rettyPhoto is a jQuery lightbox clone. Not only does it support images, it also support for videos, flash, YouTube, iframes. It’s a full blown media lightbox.

It is very easy to setup, yet very flexible if you want to customize it a bit. Plus the script is compatible in every major browser, even IE6.

It also comes with useful APIs so prettyPhoto can be launched from nearly anywhere (yes, that includes Flash)!

How to Install

Unzip the contents of the downloaded package below and copy its contents into your application’s protected/extensions folder.

How to Use

Once we have move the contents of the zipped file into the extensions folder we are ready to go. Use it at your own will into your views like this:

</p>
Yii::import('ext.jqPrettyPhoto');
jqPrettyPhoto::addPretty('.gallery a',jqPrettyPhoto::PRETTY_GALLERY,jqPrettyPhoto::THEME_FACEBOOK);

Wow! That was easy! Please allow me to explain the addPretty function. It comes with three parameters:

1) element/s selector: the JQUERY SELECTOR to the links you want to set pretty photo to. In the example above I had the following on the view’s HTML:

</p>
<p><div class="gallery"><br />
 <a href="URL_TO_IMAGE_TO_OPEN"><img src="URL_TO_IMAGE_TO_SHOW"/></a><br />

2) The second parameter is of the value jqPrettyPhoto::PRETTY_GALLERY or jqPrettyPhoto::PRETTY_SINGLE, which tells the extension whether the selector will be a list of a gallery images or just a single file.

3) The third one is what theme to use -please refer to jqPrettyPhoto.php’s code to see more options on this one.

Download

** If you have problems please use this link.

http://www.ramirezcobos.com/wp-content/plugins/downloads-manager/img/icons/default.gif download: jqPrettyPhoto Yii Extension (72.29KB)
added: 21/10/2010
clicks: 1236

Tweet this!Tweet this!
Yii Framework

jqAutocomplete Extension for Yii

0

It was only a matter of time until I try to develop an extension for the Yii Framework and I have chosen the Ajax Powered Autocomplet plugin for JQuery to exercise with this technology.

How to use the Extension

I have included a test within the downloadable package that shows how to implement this extension. The test includes a TestController, a view and a test_layout; so I hope this will easy the way for you to check it.

First download and unzip its contents

  • Move jqAutocomplete contents (I said contents) into your application’s protected/extension folder
  • Copy TestController.php and paste it in (you guessed well) your application’s protected/controllers folder
  • Move test folder (not the contents but the whole folder this time) into your application’s protected/views folder
  • Finally test_layout.php into your application’s protected/layouts folder

That’s it! Ready for the test. Go to your browser and type http://<replace_with_your_application_url>/index.php?r=test/autocomplete. If everything was good, you will be able to see the first field (JSON TEST) working as an autocomplete.

Please check TestController.php to see an example of AJAX response from the client autocomplete’s Request calls -and yes, you can also do it from a database result query. Look also at the test view’s code for an example on how to use the extension.

Download
** If you have problems to download from below; please try it here.

http://www.ramirezcobos.com/wp-content/plugins/downloads-manager/img/icons/default.gif download: Ajax Powered AutoComplete Extension for Yii (126.83KB)
added: 20/10/2010
clicks: 224

Tweet this!Tweet this!
Captura de pantalla 2010-07-12 a las 16.03.00

PalmStudios Model Agency

2

Hi there,

I would like to introduce you my last web project: http://www.palmstudios.com

For this project I have developed a sort of MVC (Model View Controller) over the RedBeanPHP DB library (PHP 5.3.2).  This project even though it looks quite simple it has a very power CMS (Content Management System) on its backend that allows the model agency to control most of the aspects of its business:

  1. - Clients Management
  2. - Models Management (Men, Women, Children & Extras) -contact details, measurements, pictures, and so on…
  3. - Promotional Packages Management – this is a special addon which allows the agency to create model promotional bundles to send to its clients

There is a ton of client and server libraries that this application makes use of, such as:

  • JQuery FancyBox
  • JQuery Livequery
  • JQuery AjaxQ
  • PHPMailer
  • RedBeanPHP
  • Savant3 Template Engine
  • PHPThumb
  • TinyMCE

The CMS has a configuration section where site administrator can configure:

  • Web site languages (has multiple language support)
  • Web site translations (you can even ask GOOGLE about a translation depending of the languages installed on the system)
  • Model properties (size, height, waist, etc…)
  • Hair Colors
  • Eye Colors
  • Users

Here is a snapshot gallery of the Site and its CMS

I am open for Freelance Jobs

If any of you would like to create a model agency application like this, let me know, I will be more than happy to collaborate with you on it. I will also sell the source code of its panel for any of you who is interested.



Tweet this!Tweet this!
Picture-121-300x157

Speed Up Your Pages With Lazy Load JQuery Plugin

2

I would like to introduce you this simple but very efficient plugin that will help us speed up the downloading time of our web pages. I am talking about mr Mika Tuupola’s Lazy Load JQuery Plugin.

This plugin loads the images of a web page as the user scrolls to their position, that is, images wont load until they are not within the visible viewport margins of the window.

How to use

First we need to insert the following references into our code

<!-- insert a reference to jquery and the jquery.lazyload plugin -->
<script src="jquery.js" type="text/javascript"></script>
<script src="jquery.lazyload.js" type="text/javascript"></script>

And now this few lines of code in our document.ready function

<script type="text/javascript">
$(function() {
          $("img").lazyload({
              placeholder : "img/grey.gif",
              effect      : "fadeIn"
           });
       });
< /script>

And that’s it! Easy right?

Tweet this!Tweet this!
Picture 1

Torrenova Rentacar

0

Torrenova Rentacar

Torrenova Rentacar

I would like to show you one of the reasons of why I have been so busy lately: torrenovarentacar.com.

One of the most complete sites in terms of rentacar systems. Fully synchronized with one of the most used rent a car management programs in Spain, CarPlus (www.cargestion.es) and with a highly powerful control panel where the rent a car owner controls absolutely everything. Its web panel features:

  • Company details
  • Contacts
  • Offices and their Google locations
  • CarPlus Settings and Sync
  • Users
  • Extras
  • Cars
  • Car Groups
  • Car Models
  • Translations (It can set new languages at will)

If you have time, please check it out as I would love to get some feedback about it.
Thanks!

Tweet this!Tweet this!
Picture-121-300x157

jQuery 1.4 -Are you ready?

0

jQuery lovers, today, 14th of January, the programmers of jQuery celebrate its anniversary releasing a new version of this wonderful library. Better iFrame support, great new shorthands, I don’t know what to say fellows but I am eager to find out what its new features are capable of.

The jQuery programmers not happy with a new release has also created a new  jQuery API site. Check what they have done on their API site here.

John Resig will announce 1.4 release details tomorrow but meanwhile, you can download it and see for yourself.

Also, if you want to learn more about what is new in jQuery 1.4 then you might find the following resources useful:

  1. 14 Days of jQuery
  2. Official jQuery Blog
  3. jQuery 1.4 Cheatsheet
  4. jQuery on Tweeter

Check what is new or changed on this new release here.

Happy birthday jQuery! Thanks for the good work!

Tweet this!Tweet this!

Cookie jQuery Plugin

4

As published on my last post, JSON gives us the great possibility to save objects on Cookies. I have already created a JSON Plugin for jQuery, then, why not create one Cookie Plugin that, in conjunction with the JSON plugin, allows us to save objects on cookies? Well, the challenge was simple and I decided to do it for those using jQuery.

The code

Remember than this plugin works in conjunction with my JSON jQuery Plugin, also on this blog.

jQuery.cookie = {
set : function(name,value,options){
options = $.extend({}, options);
if (value === null) {
value = '';
options.expires = -1;
}
var expires = '';
if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
var date;
if (typeof options.expires == 'number') {
date = new Date();
date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
} else {
date = options.expires;
}
expires = '; expires=' + date.toUTCString();
}
value = options.json ? encodeURIComponent($.JSON.encode(value)):encodeURIComponent(value);
var path = options.path ? '; path=' + (options.path) : '';
var domain = options.domain ? '; domain=' + (options.domain) : '';
var secure = options.secure ? '; secure' : '';
document.cookie = [name, '=', value, expires, path, domain, secure].join('');
},
get : function(name,json){
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = $.trim(cookies[i]);
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = json ? $.JSON.decode(decodeURIComponent(cookie.substring(name.length + 1))):decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
},
unset: function(name){
this.set(name,'',-1);
}
};

How to use

Note that you have to insert the jquery library on your head section and also the JSON jQuery Plugin -they are all included into the zip file below. Please, also refer to the example provided on my last article ‘cookies on roids’ to view more cookie options.

var obj = {json:'this is a test json property',xml:'this is a test xml property'};
var arr = ['A','B of 2 index array','C','D'];
var str = 'This is a string test';
var num = 123;
$.cookie.set('testobject',obj,{json:true});
$.cookie.set('testarray',arr,{json:true});
$.cookie.set('teststring',str);
$.cookie.set('testnumber',num);
var a = $.cookie.get('testobject',true);
var b = $.cookie.get('testarray',true);
var c = $.cookie.get('teststring');
var d = $.cookie.get('testnumber');
$.cookie.unset('testobject');
$.cookie.unset('testarray');
$.cookie.unset('teststring');
$.cookie.unset('testnumber');
alert('object:'+a.xml);
alert('array:'+b[1]);
alert('string:'+c);
alert('number:'+d);

DOWNLOAD
The zip file includes the JSON jQuery Plugin and Cookie jQuery Plugin together with an example page on how to use them.

http://www.ramirezcobos.com/wp-content/plugins/downloads-manager/img/icons/default.gif download: jQuery Cookie Plugin (23.84KB)
added: 02/01/2010
clicks: 1640
Tweet this!Tweet this!
 

JSON jQuery Plugin

14

I finally got a bit of time and I started playing around with the creation of jQuery plugins and did created a couple of them that I believe all of you will find useful, one of them is a JSON plugin.

As you all know jQuery do not have a JSON encode function. I truly do not know the reason why but to implement it was quite easy -maybe the guys from jQuery thought that it wasn’t really necessary and I agree with them. Most of us use JSON on the server side through PHP or whatever the server tech we use but sometimes, and I repeat, sometimes, we require to develop client applications that by using JSON (thanks David Crockford) we can reduce our server resources and the amount of data transmitted between client and server. But this is a subject that I will treat in the next posts.

Here is the plugin code:

jQuery.JSON = {
useHasOwn : ({}.hasOwnProperty ? true : false),
pad : function(n) {
return n < 10 ? "0" + n : n;
},
m : {
"\b": '\\b',
"\t": '\\t',
"\n": '\\n',
"\f": '\\f',
"\r": '\\r',
'"' : '\\"',
"\\": '\\\\'
},
encodeString : function(s){
if (/["\\\x00-\x1f]/.test(s)) {
return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
var c = m[b];
if(c){
return c;
}
c = b.charCodeAt();
return "\\u00" +
Math.floor(c / 16).toString(16) +
(c % 16).toString(16);
}) + '"';
}
return '"' + s + '"';
},
encodeArray : function(o){
var a = ["["], b, i, l = o.length, v;
for (i = 0; i < l; i += 1) {
v = o[i];
switch (typeof v) {
case "undefined":
case "function":
case "unknown":
break;
default:
if (b) {
a.push(',');
}
a.push(v === null ? "null" : this.encode(v));
b = true;
}
}
a.push("]");
return a.join("");
},
encodeDate : function(o){
return '"' + o.getFullYear() + "-" +
pad(o.getMonth() + 1) + "-" +
pad(o.getDate()) + "T" +
pad(o.getHours()) + ":" +
pad(o.getMinutes()) + ":" +
pad(o.getSeconds()) + '"';
},
encode : function(o){
if(typeof o == "undefined" || o === null){
return "null";
}else if(o instanceof Array){
return this.encodeArray(o);
}else if(o instanceof Date){
return this.encodeDate(o);
}else if(typeof o == "string"){
return this.encodeString(o);
}else if(typeof o == "number"){
return isFinite(o) ? String(o) : "null";
}else if(typeof o == "boolean"){
return String(o);
}else {
var self = this;
var a = ["{"], b, i, v;
for (i in o) {
if(!this.useHasOwn || o.hasOwnProperty(i)) {
v = o[i];
switch (typeof v) {
case "undefined":
case "function":
case "unknown":
break;
default:
if(b){
a.push(',');
}
a.push(self.encode(i), ":",
v === null ? "null" : self.encode(v));
b = true;
}
}
}
a.push("}");
return a.join("");
}
},
decode : function(json){
return eval("(" + json + ')');
}
};

How to use

Copy and paste the above code onto a file and name it whatever you like, for the sake of the example we will call it jquery.json.js. And then configure your head section like this:

<!-- jquery library (if you dont have it, then download it :)  -->
<script language="javascript" src="jquery.1.3.2.js" ></script>
<!-- our plugin file -->
<script language="javascript" src="jquery.json.js"></script>

That’s it, now we can call our plugin like this:

// test variables
var obj = {json:'this is a test json property',xml:'this is a test xml property'};
var arr = ['A','B of 2 index array','C','D'];
// encoding an object
var a = $.JSON.encode(obj);
alert('json encoded object:'+a);
// decoding an object
var b = $.JSON.decode(a);
alert('json decoded object property:'+b.json);
// encoding an array
a = $.JSON.encode(arr);
alert('json encoded array:'+a);
// decoding the array
b = $.JSON.decode(a);
alert('json decoded array:'+b[1]);

On future posts we will make use of this plugin to show what we can do with it.

Tweet this!Tweet this!
autocomplete

Ajax Powered Autocomplete Plugin for JQuery.js

3

I am glad to announce the launch of the successfull Ajax Powered Autocomplete for Prototype.js now as a plugin for JQuery. No much to say… if any of you want to have a look at this piece of code you can check it here.

Any feedback is highly appreciated.



Tweet this!Tweet this!
Go to Top