Tuesday, October 23, 2007

I need one menu with horizontal accordion, but the plugins that I have looked doesn't like me, too much requirements or code, really I need something more simple, so in few minutes I write a simple plugin.

v0.1

It is very simple, with a few parameters: speed set the velocity of the animation, headerclass set another classname for header divs (by default "header"), contentclass set another classname for content divs (by default "content"), contentwidth is the final with of each content panel.

HTHML Sample:



.haccordion .header, .haccordion .content{
float: left;
height: 250px;
}

.haccordion .header{
width: 20px;
background: #ccc;
color: #fff;
cursor: pointer;
}

.haccordion .content{
display: none;
width: 0px;
overflow: auto;
}

.haccordion .content p{
margin: 5px;
}


*1

This is a sample of content for Content1 with a large text, testing, testing, testing, testing, testing, testing, testing, testing, testing, testing, testing, testing, testing


*2

This is a sample of content for Content2 with a large text, testing, testing, testing, testing, testing, testing, testing, testing, testing, testing, testing, testing, testing


*3

This is a sample of content for Content3 with a large text, testing, testing, testing, testing, testing, testing, testing, testing, testing, testing, testing, testing, testing




JavaScript Sample code:

  $(function(){
$(".haccordion").haccordion();
});

Demo:

Technorati Tags: , ,

Download jquery.haccordion.js code.

Labels: , ,

32 comments, Post a CommentPosted by posted by SeViR @ 12:44 PM
Thursday, October 18, 2007

Recently I have had a small dilemma, because I needed to load in a web page, a list of locations with the associated map image. Google maps is very good but overload too much the page with JavaScript, I only need images and not one complete map container because possibly the page need display ten or more map images.

I could read the Yahoo Map Image API, is perfect for my project because I only download a simple gif image, the problem is that, first, in the API help only we can see the output of the rest call in XML and PHP stringfy. This is a problem for me because the IP limitation of Yahoo and Google API's requires that in big projects must be the users that they query the API using JavaScript, because if I use the server, the API blocks the calls when I pass the max number of calls.

Well, using JavaScript I have two possibilities, call the API with XML responses (problem with XMLHttpRequest domain restrictions, it is neccesary a proxy and the same problem with the IP calls in the proxy server), or a hidden possibility with JSON responses calling with scripts tags (not AJAX).

Althought Yahoo Map Image API doesn't show any possibility about JSON, all REST API calls of Yahoo share the same parameters, so I tried the params "&output=json&callback=myfunction" and voilà I have the JSON response. With the callback function I can execute a function from my code receiving as params the API response.

The problem now is making multiple calls asyncronously to the API. The callback function doesn't know the related image for to associate the src url of the map image (or associate div). So I thought in one solution, this is a small code of a extension for load multiple map images by ID.


var yahoo = {
calls: new Array(),
apikey: "YahooDemo",
callImageApi: function(latitude, longitude, imgobj, iwidth, iheight){
iwidth = (typeof iwidth != "undefined")?iwidth:"70";
iheight = (typeof iwidth != "undefined")?iheight:"70";
var index = yahoo.calls.push([imgobj, function(data){
this[0].src = data.ResultSet.Result;
}]) - 1;
var miscript = document.createElement("script");
miscript.src = "http://local.yahooapis.com/MapsService/V1/mapImage?appid=YahooDemo&latitude="
+latitude+ "&longitude="
+longitude+ "&image_height="
+iheight+"&image_width="
+iwidth+"&output=json&callback=yahoo.calls["
+index+"][1]";
miscript.type = "text/javascript";
head = document.getElementsByTagName("head")[0];
head.appendChild(miscript);
}
}

With this HTML of example, we can call to the library using yahoo.callImageApi(latitude, longitude, imageobj, width, height):


 


yahoo.callImageApi("36.8402","-2.46792", document.getElementById("test1"),300,300);
yahoo.callImageApi("38.01504422431762","-1.1742335557937622", document.getElementById("test2"),400,400);

Download the example.

Technorati Tags: ,

Labels: ,

0 comments, Post a CommentPosted by posted by SeViR @ 12:57 PM
Thursday, August 09, 2007

After of the plugin publication, I have had some request about how you alert the errors as "classic" YAV style or how you display all the errors inside a DIV.

In the first time, I question me, Why I want show all the errors inside a only layer?, focusing in accesibility it is better show the errors inside the label of the each field, but... Why not?. This is the idea:

I copy all the errors in the onError function, inside to a div, and remove the old.

	$(document).ready(function(){
$("#form1").yav({
onError: function(){
$("#errorContainer").append($(".error"));
$(".error").not($("#errorContainer .error")).remove();
$("#errorContainer").show();

return false;
}
});
$("#errorContainer a.close").click(function(){
$(".error").remove();
$("#errorContainer").hide();
})
});

Run the example.

The second idea. Really I have deprecated "classic" YAV style (a simple alert) because this is not usable and with a minimal accesibility. But if you want.... you can get the messages in the old jsErrors variable of YAV, but the syntax of this errors have changed a bit in the plugin. An error message is an map object like {id:"the_related_id_field", msg:"the error message"} or the string representation of this object. So:


$(document).ready(function(){
$("#form1").yav({
onError: function(){
var errorList = "Please check the next errors: \n\n";
for (var i=0; i errorList += ((typeof jsErrors[i]=="object")?jsErrors[i].msg:(eval("("+jsErrors[i]+")").msg)) + "\n";
}
alert(errorList);

return false;
}
});
});

Run the example.

If you have another idea, please say it to me.

Labels: , , ,

1 comments, Post a CommentPosted by posted by SeViR @ 9:32 PM
Tuesday, August 07, 2007

An easy way, XHTML standard, accesible and usable, library for form validations using JavaScript with the powerful libraries jQuery and YAV.

 

Background

Web forms are the standard way for to obtain input data of the users. As usual, you allways need to validate the input data before to accept them (store in the database, work with them, ...) , so the server-side validation is neccesary because errors in the input data can generate errors in the server code (clients without javascript, direct posts,...). You have different alternatives for server-side validation, using frameworks (CodeIgniter for PHP or Apache Wicket for JAVA are some examples of web forms validation routines) or programming all the code lines for to validate the input data from the user (more tedious).

But there are some thoughts about you prefer validate also the web form in the client side:

  1. Is faster. You don't need send the form and wait the response from the server.
  2. Major interactivity.
  3. More usable interfaces.

In internet, there are some examples of different sort of javascript validation, programming directly each validation routine (Javascript form validation – doing it right, Form validation,...) or with a javascript library (JavaScript Form Validations Made Easy!, JavaScript Form Validation, the Aspect-Oriented Way). The libraries are preffered by the programmers because reduce the code that they write but normally these libraries are focused to the data validation but not in the later error representation, so the main validation function only returns true or false, or a list of fields with the errors and the programmer normally show the errors all together in an alert box or in a custom place in the web page (a div) or colour the error field. These methods of error representation can be improved focusing to accessibility and usability:

  1. A normal alert box showing the errors is not usable and not accessible because, after to click in the OK button, the user have not visible what is the field with the error. You need mark with a accessible way the field.
  2. Colour the field is well, because the user can see the problematic fields fastly (usable), but is not accesible (what about with visibility problems people). You need write near the field, preferably in the label of the field.
  3. Move the focus to the first error. If you update the page content with JavaScript, and the user is in the bottom of the page, probably, the changes are not shown by the user. You need scroll the page and focus the first element with problems or error message.

There are two libraries (that I know) with more advanced options for web forms validation, jQuery Validation plugin and YAV. These libreries are very good but I have found some problems with them:

  • You have to set a list of rules for each field to validate and the error messages in the JavaScript (Validation plugin and YAV). YAV is more tedious because the conditional rules require to set the proper indexes of the condition rule in the array of the rules. Also, you need then different JavaScript code for different language messages (english, spanish,...) although normally the language translations are in the templates.
  • Awful class names like class="{required:true,email:true}" (Validation plugin).
  • Custom validate attribute is not W3C standard (Validation plugin).
  • The error results are not associated to each field (YAV). Then the programmer have not a easy way to write an error message near the field.
  • Relationship rules. Only YAV has relationship rules like and, or or implies. Also you can set a rule of relation of other relation joint like (field1 and field2) or (field2 and field3).
  • jQuery Validation has a perfect control over where the error messages are shown but it is not the same in YAV. YAV only show the errors as a list using a layer or an alert message. You can not set individual message related with the error field (YAV).

So I'd need some similar but only with the good things of these plugins and without the problematic things (no W3C attributes, ...). This was my target for the spare time in my holidays.

jQuery.YAV plugin makes easy the web forms validation

jQuery.yav is a new plugin for to integrate YAV form validation wih jQuery, making the form validation more easy, accessible, usable and W3C standard. Now you can validate forms with a more easy form, and if you like, you can get all the power of the custom and extended setting of this plugin, setting more complex validations. jQuery.YAV add also, a little bug repair for YAV library for multiple values in class attribute and not requires yav-config.js file. Tested in IE 6 and 7, Firefox 2, Netscape 7, Safari 4 for Windows, Konqueror 3.5 in Linux and Opera 9 but must work in jQuery compatible browsers.

Changelog
Open changelog

IMPORTANT: YAV 1.4.0 library introduced a bug working with multiple classes, you can download a patched version or wait for the future release :-)

Download

 jquery.yav.js (uncompresed version) or  jquery.yav.pack.js (compressed version, only 4kB) and the documentation

The plugin requires jQuery (MIT/GPL license) and YAV (GPL license) libraries.

Documentation

jQuery.YAV set all predefined rules of YAV as simple class names. So you can validate simply set the proper class name. If the rule fails then the title of the field is shown as error message. This is for accesibility improve, so screen readers can read the guidelines of the field. jQuery.YAV capture the "onsubmit" event and if the validation fails the form is not submitted.

Basic example (run the example)








JavaScript code:
 $(document).ready(function(){
$("#form1").yav();
});

Username field has two classes (required and alphanumeric) and the title attribute with the message, also in email field has required and email classes. This classes works as normal css classes but also as validation rules, so any form field with this rules will be validated.

The pre-defined validation classes are the same of YAV: "alnumhyphen", "alnumhyphenat", "alphabetic", "alphanumeric", "alphaspace", "date", "date_le", "date_lt", "double", "email", "empty", "equal", "integer", "keypress", "maxlength", "minlength", "notequal", "numeric", "numrange", "regexp" and "required".

If any rule requires some parameter you can set in the alt attribute with a especial syntax. Alt attribute in form fields in the standard XHTML is of type CDATA so, you can write any code and this is XHTML valid!.

Also if you use more rules, you can set params as array of params (you need set an empty array param for the rules that not requires params). The params is in alphabetic order of the rules:

Basic example with field event validation(run the example)








JavaScript code:
 $(document).ready(function(){
$("#form1").yav();
});

Alternatelly you can validate a form field on event trigger using the event parameter. This parameter is a event or a comma separated event list.

Custom rules example (run the example)








JavaScript code:
 $(document).ready(function(){
$("#form1").yav({
errorDiv:"mainError",
errorMessage:"Some errors are found, please correct them",
custom: {
myCustomRule: function(return_value, param1, other_param){
var field_id = return_value.id;
if ($("#"+field_id).val() == param1){
return null;
}else{
return return_value;
}
}
}
});
});

You can set others new validation rules and use them as class names like pre-defined validation classes, the HTML code is the same, and if your custom rule has params, you can set the params with the same way of pre-defined rules. In the yav plugin call, you can set the config parameters as a map variable (pairs of key: value). A special param is "custom" and this is also a map variable with the custom rules definitions name_of_the_rule: function(...).

A custom rule allways has a first param (called in the example as return_value) with the id and the msg for to show the error. For a custom rule works, the rule must return null if the rule is passed or the first param on error. Alternately, you can use this param for to get the id of the associated field.

In this example, we can set a top message, indicating that there are found errors. This settings are configured with "errorDiv" and "errorMessage" param. If errorDiv is not found in the page, the message is not shown. The webpage scroll to the first error or the errorDiv in each case. This setting is for usability and more accessibility improve.

Advanced config options and setting yav configuration variables and AJAX(run the example)








JavaScript code:
 $(document).ready(function(){
$("#form1").yav({
errorDiv:"mainError",
errorMessage:"Some errors are found, please correct them",
errorClass:"verror",
errorTag:"span",
errorPosition:"parent().before",
custom: {
myCustomRule: function(return_value, param1, other_param){
var field_id = return_value.id;
if ($("#"+field_id).val() == param1){
return null;
}else{
return return_value;
}
}
},
onOk: function(form){
$.post(form.action,{
text: $("#text").val()
},function(server_response){
alert("User says: "+ server_response);
});

return false;
},
onError: function(){
alert("Please correct the errors");
return false;
}
},{
inputclasserror: "markererror",
errorsdiv: "yaverror"
});
});

This example shows how set more advanced settings of the plugins. In the call of yav plugin, we have two map params, the first is the plugin config params, the second is used for to change the default YAV settings (see YAV documentation), the names of the configuration variables in the second  parameter are the same name as YAV original library.

In the first param, we have some control variables for jQuery.YAV plugin, errorDiv and errorMessage sets a top error and advice to the user. errorClass set the class of the errors when they are shown (by default the class is "error"), errorTag set the tag that enclose any error message (by default is a "p" tag, you can use "div, span, etc..."), errorPosition set the position related to each error field using the name conventions of jQuery (after, before, parent().before, parent("tr").next("tr").html, ....).

Two more config variables you can use, onOk and onError. This config variables are functions with one param (a reference of the validated form). If these functions returns false, the form submit is cancelled, if returns true or none the form is submitted. You can use this functions for to execute any code post-validation, by example, we can use onOk function for to submit the input data using AJAX, and cancelling the normal form submittion. You can use one, two or any of these functions.

Working with relationships between rules (run the example)









JavaScript code:
 $(document).ready(function(){
$("#form1").yav({
errorDiv:"mainError",
errorMessage:"Some errors are found, please correct them",
errorPosition:"parent().before",
custom: {
myCustomRule: function(return_value, param1, other_param){
var field_id = return_value.id;
if ($("#"+field_id).val() == param1){
return null;
}else{
return return_value;
}
}
}
});
});

This example shows a basic relation between two fields. This fields are related with a conditional and so, we will show another message if the two rules are passed. This relationship is set from the HTML code inside the alt attribute. In the alt attribute of the first field, we have a condition configuration, this condition has the next structure:

condition: { name: 'any_string_identifier', type:'and|or|implies', msg:'Error message to show'}


Alternately, you can set also, a id variable in the condition, with the id of the field that the error will be show, by default is the first field with the condition configuration. The next field only configure a condition using the name identifier, so, any field configured with the same condition identifier are conditioned to the same relationship.

In the previous example, the two rules are checked and generates an error although we remove the relationship, but if I don't want shows the individual errors but I want show the relationship error, I can set a requirement, in the alt attribute, we write the require setting with the valid values: pre-condition or post-condition (for implies relationships).

alt="{require:'pre-condition',condition: { name: 'any_string_identifier', type:'and|or|implies', msg:'Error message to show'}}"

Multiple condition and groups of relationship (run the example)

You can set relationships over other relationships. So we have 4 fields (A, B, C and D), we have related A and B, later we have related C and D, we also want a relationship over the first group and the second group with a or condition, by example, so we have: (A and B) or (C and D).









JavaScript code:
 $(document).ready(function(){
$("#form1").yav({
errorDiv:"mainError",
errorMessage:"Some errors are found, please correct them",
errorPosition:"parent().before",
custom: {
myCustomRule: function(return_value, param1, other_param){
var field_id = return_value.id;
if ($("#"+field_id).val() == param1){
return null;
}else{
return return_value;
}
}
},
onOk: function(){
alert("The validation is passed, please note that is the field is empty the rule is passed");
return false;
}
});
});

As you can see in the example in the first field, we have set two conditions in the alt attribute, so condition config also can be an array of relationships. In the second condition we have set a new configuration value group as array of relationship identifiers.

{name: 'identifier_of_relation_group', type: 'or', group:['one_identifier', 'other',....], msg: 'message to show on error'}

Also as you can see, a condition (relation) can have a require value, the same as a normal rule.

Labels: ,

61 comments, Post a CommentPosted by posted by SeViR @ 10:12 PM
This design is under copyright of SeViR CW © 2007