Sep 12

YUI 3.0.0 From Yahoo!

Posted By Ahmed El-Kilani On 12 Sep 2009 3 Comments »

The Yahoo! next-generation JavaScript and CSS library, is a big step forward.
YUI team has improved the library; syntax is enhanced, API is more flexible and easy to use.

Featured Components:

  1. DataSource: YUI’s data abstraction layer provides a standard interface into data sets, regardless of the data’s origin (local, XHR, XSS, etc.) and format (JSON, XML, CSV, etc.);
  2. ImageLoader: ImageLoader allows you to defer the loading of images that aren’t in the viewport when the page paints, throttling bandwidth usage and improving performance;
  3. History: The History component gives you control of the brower’s back button within the context of a single-page web application;
  4. StyleSheet: StyleSheet makes it easy to create and modify CSS rules on the fly, allowing you to dynamically style page elements with fewer repaints.

More:
http://developer.yahoo.com/yui/3/

Apr 10

Drag and drop over images (Javascript)

Posted By Ahmed El-Kilani On 10 Apr 2008 No Comments »

To drag an image or drag and drop over images you need to handle the mousedown, mousemove and mouseup events, But you cannot drag an image in an html document directly, this means you cannot handle those events for the img element itself. You cannot say:


    

All we have to do is to handle those events for the document element and detect what we are draging over.
The source/target element which is sent to the handler is the element we are draging over:
//Called when the mouse moves over the document.
function documentDragOver()
{
    var el = e ? e.target : event.srcElement;
}
Here is the complete code in order to drag an image:
var ie = document.getElementById;
var dragStarted = false;
var objToDrag;

function mouseMove()
{
  if (objToDrag && dragStarted)
  {    
    objToDrag.style.left = (ie ? event.clientX : e.clientX) - diffX;
    objToDrag.style.top  = (ie ? event.clientY : e.clientY) - diffY;
    return false;
  }
}

document.onmousedown = function() 
{  
  objToDrag = ie ? event.srcElement : e.target;
  
  if (objToDrag && objToDrag.className == "ddImg")
  {
    dragStarted = true;
    diffX = (ie ?  event.clientX : e.clientX) - parseInt(objToDrag.offsetLeft);
    diffY = (ie ?  event.clientY : e.clientY) - parseInt(objToDrag.offsetTop);
    document.onmousemove = mouseMove;
    return false;
  }
}

document.onmouseup = function(){
	dragStarted = false;
}

Mar 22

Textbox label inside

Posted By Ahmed El-Kilani On 22 Mar 2008 No Comments »
Sometimes labels beside textboxes require much space and bad design, so the best solution is to type the label text inside the textbox, it is pretty easy but we need some retouch, like coloring the label text with a different color and handle onfocus and onblur events.
Here is a javascript function that does this for you:
    function labelText(id , text)
    {    
        var element = document.getElementById(id);
        var labelColor = 'gray';
        var originalColor = 'black';
        if(element.style.color)
            originalColor = element.style.color;
        
        element.style.color = labelColor;
        element.value = text;
        element.isNull = true;
               
        element.onblur = function(){
            if(this.value.replace(' ','') == '')
            {
                this.value = text;
                this.isNull = true;
                this.style.color = labelColor;
            }
        }
        element.onfocus = function(){
            if(this.isNull)
            {
                this.value = '';
                this.isNull = false;
                this.style.color = originalColor;
            }
        }
        
    }
    
And easily you can label any input field like:
    
    
    labelText('myText' , 'Search...');
    
Feb 29

Most 5 features jquery newbies should learn

Posted By Ahmed El-Kilani On 29 Feb 2008 No Comments »
Here are the most top 5 brillant features of jquery, that a jquery-newbie should know:

1- Switching between DOM elements and jQuery:
To convert your jquery object to DOM element just use the indexer like the following since jquery object contains an array of matched elements:
    $('#elementid')[0].innerHTML = "New data";
    
On the contrary you can convert the DOM element to jquery using $() function:
    $(document.getElementById('elementid')).html("New data");
    
2- Filters:
    $(':hidden').show(); // Show all hidden elements
    if($('#elementid').is(':visible'))$('#elementid').hide(); // Hides an element if it is visible
    $(':empty').remove(); // Remove all emty elements
    $("table1 tr:first").css("font-style", "italic"); //Find the first row of table1
    $("table1 tr:last").css("font-style", "italic"); //Find the last row of table1
    
3- each method:
Loops DOM elements inside a jquery object since jquery object contains an array of DOM elements:
    //Display a warning if any input field is empty
    $('input[type=text]').each(function(){
    if($(this).val() == '')alert(this.id + " is empty!");
    });
    
4- trim whitespace:
var trimmed = $.trim(" Text to be trimmed ");

5- Inserting elements inside/outside other elements:
With jquery creating elements on the fly, inserting, removing or replacing them are much easier:
append() : append an element right after the last element inside the given element:
$('#container').append("<div>A new child</div>");
prepend() : append an element right before the first element inside the given element:
$('#container').prepend("<div>A child at the first order</div>");
after() : append an element right after the given element:
$('#elementid').after("<div>A new nextsibling element</div>");
before() : append an element right before the given element:
$('#elementid').before("<div>A new previoussibling element</div>");
replaceWith() : replaces and element with another:
$('#elementid').replaceWith("<div>Element to replace</div>");

Jan 22

First look at the Online Demo.
Try and move both capricorn images, if you are using IE 6 or lower you will notice that the top image is not correctly transparent while transparency displays properly with the bottom one.
With PNGs we can get high quality transparent images, 32-bit colors and high quality shadows, which is not available with transparent GIFs.
IE 7 has fixed the problem with transparent PNGs but plenty of users are still using their older versions of Internet Explorer.
To fix this problem we have to use AlphaImageLoader CSS filter like the following:

				
This will fix the problem instead of using:

AlphaImageLoader not only fixes the problem, but also displays images within the boundaries of the object and between the object background and content, this means that you can select the text just behind the transparent region of the PNG image.

Very cool,

Enjoy it.

Jan 05

Ajax/CSS cool wizard

Posted By Ahmed El-Kilani On 05 Jan 2008 No Comments »

First see Online Demo
A cool look-and-feel wizard for navigation between steps is one of the most precious addin to your pages. I come today with a creative technique, which i have created a month ago, to feature it out.
Let's start out:
1- I have used jquery for its easy ajax support, if you do not know what jquery is I advise you to visit this.
2- CSS filter Apply and Play:

el.style.filter "progid:DXImageTransform.Microsoft.Wipe(GradientSize=0.2, duration=0.7, wipeStyle=0, motion='forward')"
el.filters[0].Apply()
el.innerHTML data.toString()
el.filters[0].Play();

Wipe filter creates the feel of gradient transition.
For more about transition filters click here.
-Apply() function saves the current state of the element "el" in the memory
-el.innerHTML = data.toString(); does not change the "el" state.
-Play() function plays the transition effect between the saved state (data before calling apply()) and the new one.

3-AjaxLoader.aspx
Each step is a user control which is loaded dynamically into AjaxLoader.aspx. Jquery $.post() function requests AjaxLoader.aspx and inject the response into "ajaxsite" DIV element.
AjaxLoader.aspx must not contain html, head, body or form tags since it will be loaded into "ajaxsite" div element.

4-AjaxPost():

function AjaxPost(url ,paramz, target , dir)
{        
    
//paramz: parameters to send to the page using POST method
    
$.post(url ,paramz, function(data){         
        
//Callback after the response of the ajax request
        
var el $('#' + target)[0];
        
        var 
motion 'forward';
        if
(dir == "rtl")motion 'reverse';
                
        
el.style.filter "progid:DXImageTransform.Microsoft.Wipe(GradientSize=0.2, duration=0.7, wipeStyle=0, motion='"+motion+"')";
               
        
el.filters[0].Apply();        
        
el.innerHTML data.toString();
        
el.filters[0].Play();        
    
});
}

This function call $.post function then updates the data into the target DIV by appying Wipe filter.
motion parameter specifies the direction of the transition.

Pretty cool, isn't it?

Demo with source code is available within the attachment.

jqAjax.rar (176.76 KB)
Dec 27

Rounded-edge HTML Layout without images

Posted By Ahmed El-Kilani On 27 Dec 2007 No Comments »

Smooth-edged tables, Div elements are most famous simple and stylish layout. To make your square table smooth you gotta have four small images
for the corners, slicing images then fitting them into tables plus every image for each color if we are about to make multiple themes are sort of boring. Here comes the magic of CSS where we can create smooth layouts without images.
Here is the result:

Here our contents go 


How are the previous fantastic sets of DIV elements shaped?
Simply if we understand how computers draw a curved shape we can understand this. It consists of four div elements for the curved header and upside down another four for the footer, playing with their widthes (from smallest to largest) for the header and on the contrary for the bottom.
Let's see the DIV elements:

<div id=round>
<div id=top>
<div class=s1></div>
<div class=s2></div>
<div class=s3></div>
<div class=s4></div>
</div>
<span>Here our contents go</span> 
<div id=bottom>
<div class=s4></div>
<div class=s3></div>
<div class=s2></div>
<div class=s1></div>
</div>
</div>



Inside the top DIV four div elements classed from s1 to s4 and inside the bottom div the same four upside down.

Now let's see the css features the shape:

   #round{
    width
:250px;    
    background-color
:gray;
    color
:white;      
   
}
   
#round span{
    padding
:10px;    
   
}
   
#top,#bottom{
    background-color
:white;    
   
}
   
.s1,.s2,.s3,.s4{
    height
:1px;    
    background-color
:gray; 
   
}
   
.s1{margin:0 5px;}
   
.s2{margin:0 3px;}
   
.s3{margin:0 2px;}
   
.s4{margin:0 1px;height:2px;}



By playing with different margins for the classed divs we get the range of widthes for those elements which shape the curve.

Pretty easy, is'nt it?

Nov 16

Best thing I like about jquery is each() function which loops the jquery elements and do the best for you. For code reusability I'm posting this article to show how with one javascript function we could confirm that all our required fields are not empty when submitting the form.

First say we have a registration form for reservation application, we have some fields must be requied, others must only contains a valid email address and others are optional. So without considering any calling for our confirm function we will only mark out input fields. Here is how to do:

<input type=text runat=server alt=required />
<
input type=text runat=server alt=email />
<
input type=text runat=server />


The first input is required, the second one must contain a valid email address while the last is optional.

Now in our javascript file , lay out these few lines of code:

$(document).ready(function(){
$(
'form').onsubmit(function(){
    
var success = true;
    
$('input[alt=required]').each(function(){
    
if($(this).val() == ''){
    success 
= false;
    
}
})
;

if
(!sucess)
    
alert('Fill in all required fields before submitting.');

return 
validateEmails();
});
});

function 
validateEmails()
{
    
var success = true;
    var 
emailFilter /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    
$('input[alt=email]').each(function(){
    
if(!emailFilter.test($(this).val()) ){
    success 
= false;
    
}

    
if(!success)
    
alert('You must enter a valid email address');

    return 
success;
}


Save this file and link it to any page you wanna validate before submitting and don't forget linking to jquery source.

Cool isn't it?