Share the ideas and thoughts, become united ...
Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

Wednesday, April 28, 2010

jQuery: Nice looking slide show in no time !!

Sometimes we need to add sideshows to our website. Today we are going to see how to achieve it very quickly with a little bit of coding. We will use the jQuery to reduce the amount of coding we have to do. Now let us see how can we do it -

What we will need -
  1. jQuery script [jquery-1.3.2.min.js]
  2. Images which will appear in the slide show
  3. Some JS and HTML coding
 First we will need to add the jQuery library file.
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
 Next we need to setup our own jQuery code to define the slide show materials and properties.

 <script type="text/javascript">
    var srrc = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg"];
srrc is the array variable which holds the image paths of the slide show images. You can add as many path as you want. 
    var id =0;
    var max = 5;
id is the variable whose value tells the browser to load which images from the srrc array. It is acting as a index variable for the srrc array. max variable defines the maximum number of images defined in the image array.
function run() {
        id = id + 1;
        id = id % max;
        var cur = srrc[id];
 Nothing much to describe here. cur variable holds the path for current image which we are going to display.
        $("#images").hide();
        $("#images").attr({src: cur, alt:'', border:0});
        $("#images").fadeIn("slow");
$("#images") will return the handle of the html element with the id of images. Don't worry about the element for now, it is a <img> element, we will be introduced with it in the latter section.
First we used the jQuery hide() function to hide the element.
Then we use the jQuery attr() function to add the html attribute to the <img> element. The important part is the src: cur. cur variable is holding the image path for current image. So, we just add the image path to the img tag. It can be translated as <img src="the image path in the cur variable">.
Now the img element has the image but it is hidden. Now we show the whole element using the jQuery fadeIn() effect. This adds nice looking transition effect while changing the images.
        setTimeout(run,10000);
    }
 Now to run this script indefinitely we use setTimeout() javascript function. We want to keep each images for 10 secs. So the second parameter is 10000 (it is in mili secs). The first parameter is a callback function.
Whenever 10 secs has passed since the timeOut() function is called, the callback function is called automatically.
    $(document).ready(setTimeout(run,3000));
</script>
 Lastly we use the $(document).ready() function to initiate the first call to the run function.

Now all we need is to add the <img> element into body section of the html page
<img src="1.jpg" width="395px" height="245px" alt="" id="images" border="0" />
 We are all done.
Here is the total work.
If you have any suggestion or question please leave a comment.

Thursday, April 8, 2010

Rapid jQuery: HTML Form Validation

I have showed the idea of basic form validation with jQuery on my previous post. Now I am gonna show you guys how to speed up the validation process by using plug-in. Be ready to be amazed !

What we need :
  1. jQuery 
  2. jQuery Form Validation plug-in
  3. HTML codes :)
First we need to add the jQuery and the plug-in to our webpage which we want to validate.
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="jquery.validate.min.js"></script>
Now lets have a look at the form which has to be validated.

<form action="submit.php" method="post" id="doit" >
<fieldset>
    <label for="name">Name</label><br />
    <input type="text" id="name" name="name" class="required" minlength="2" /><br />
    <label for="email">Email</label><br />
    <input type="text" name="email" id="email" class="required email" /><br />
    <label for="zip_code">Zip code</label><br />
    <input type="text" name="digits" id="zip_code" class="required digits" /><br />
    <input class="submit" type="submit" value="Submit" />
</fieldset>
</form>
We have to set up some meta data in order to use the built in validation methods. We are using the label to notify the user about the field and also to display the error message. The important part is the for property. It is the same as the id of the component it is representing.
The next important part is the name property it must be one of the predefined class. some of the predefined classes are:
  • name - validation for common name
  • email - validation for email addresses
  • url - validation for url addresses
  • digits - validation for only digits
There are many predefined class. You can check the plug-in's documentation for complete list.
Next important property is class property. You can define your field to be required in the class property.
Note that the email input type has a class value of "required email". It means that the field is a necessary one and it must contain a valid email address.

Hope you have understand the basic behind the validation plug-in. Now we are only one step away from the validation process. Lets check it out -

<script type="text/javascript">
    $(document).ready(function () {
        $("#doit").validate();
    });
</script>
 Now we have to call the validate() method of the form. so we use the $("#doit") to select the whole form. And then call the validate() method to validate it.
Yes the validation is completed. Don't believe me? Why don't you just try it out.

Lastly you can add customization in the CSS section to change the way the message appears.
<style>
    label.error {
        color:#FF0000
    }
</style>
Here is a snapshot of the validation process :


Update - Here is the source code.
 If you have any suggestion or question, please let me know.

Monday, April 5, 2010

Do it with jQuery: HTML Form validation - Source @ Bottom

This is my follow up on my previous post on Form validation with javascript.
This post for those who want to try the form validation with jQuery.

jQuery is a javascript library developed for rapid application development. I,e - One can write less code by using it, so the development of the application is accelerated.

You can learn more about jQuery here.

To get started we need -
  1. HTML page which contains the form.
  2. jQuery Library
  3. Some jQuery codes.

After getting the jQuery libarary we have to add it to our HTML page. Scripts are generally added with in the <head></head> html tags.
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<link type="text/css" href="style.css" rel="stylesheet" />
As you can see that this is done by using a <script> tag. We are gonna use the stylesheet (CSS) to decorate the messages. This will increase the user interactivity.


Now we need the html form which has to be validated.
<body>
<form action="submit.php" method="post">
<table cellpadding="0" cellspacing="0">
<tr><td>
First name: </td><td><input type="text" name="fname" id="fname" /></td><td>
<label id="s_fname"></label>
</td></tr>
</table>
</form>
We need the id field to get the component's handler so that we can manipulate it. Id provides a way to uniquely identify the component.

We now write a little code to register jQuery events with callback functions. All these code goes inside the <head></head> HTML tag.
<script type="text/javascript">
        $(document).ready( function() {
        $("#fname").blur(function () {
jQuery starts now. jQuery uses callback function to handle various event. One of the most import callback is the $(document).ready( function () {} );. When the page loads completely this event is raised. So, in the process of handling we can register more callback function. As we are dealing with the textbox, so we are gonna register the callback function for blur() event. When ever the text box loses focus this event is raised.
So, by registering callback method to it we can check the value of it and decide whether it is valid or not. We uses $(id) to get the component. Then we use the blur(fn) event to register the callback method.

Now we get the value from the textbox and examine it.
            var value = $("#fname").val();
            value = jQuery.trim(value);
            $("#fname").val(value);
First line gets the value of the component by calling the val() method. Then we use a jQuery utility function jQuery.trim(str) to trim the beginning and trailing whitespaces from the input. Then by the third line we again set the new value back to the textbox by using the val(value) method of the component.
            if (value == "" || value == null) {
                $("#s_fname").text("Please enter a name.");
                $("#s_fname").removeClass("valid");
                $("#s_fname").addClass("error");
                $("#fname").removeClass("valid_back");
                $("#fname").addClass("error_back");
            } else {
                $("#s_fname").text("Ok");
                $("#s_fname").addClass("valid");
                $("#s_fname").removeClass("error");
                $("#fname").removeClass("error");
                $("#fname").addClass("valid_back");
            }
        });
      
    });
  
</script>
We check the value for empty or null string. If the value of the textbox is either null or empty ("") then the value is invalid and we notify the user by setting the background of the textbox to red. We also display a red text to notify the user about the error. This is done by using the text(str) method of the component. text(str) sets the text of a component. We use removeClass(class name) and addClass( class name ) to remove and add the visual effect to the textbox defined in the CSS class. Here in the code "valid" and "error" are two CSS class. We use "valid" class to denote that the validation is successful and we use the "error" class to notify user that validation failed.

We now need to code the style.css file. This file contains the CSS class which we have used.

.error {
color:#FF0000;
}

.valid {
color:#006600;
}

.error_back {
background-color:#FF0000;
}

.valid_back {
background-color:#006600;
}
 Every class in the CSS must have a 'dot' (.) before them. In the class definition, we set the color value to red in the error class and we set the color value to greenish in the valid class. These classes are used to show message in red or green color to notify the user. We assign then depending upon the validation of the textbox.

The next to classes are used to change the background-color of the textbox. If the validation succeed then we set it to greenish other wise we set it to red to indicate that validation has failed.

We are all done. This post only shows how to use the jQuery functions for form validation. For a basic form validation you can see the previous post. Here is a snapshot of how it looks -

Update - Here is the source code.
If you have any question or suggestion, please let me know.

Tuesday, March 30, 2010

CooL & Sexy yet Easy Message Box using jQuery

With the advent of Web 2.0 the website now gotten more interactive. Now a days website are elegant in looks. And it really hurts (hard works) to create a nice interactive website. jQuery grants us the wish - "write less do more".

jQuery is very easy to learn and implement. Today I am gonna show you how to add a jQuery UI component easily to your website.

First of all let us first see what do we need. We need the jQuery UI component.
Secondly, you need an editor to edit and write your website.
Lastly, you need some hard works.

After downloading first extract the zip file and go to the following directory -
jquery-ui-1.7.2.custom\development-bundle\ui
Now as we are going to work with only dialog (jQuery know them as dialog) so we only need some part of the total ui system. These are -
  • ui.core.js
  • ui.draggable.js
  • ui.resizable.js
  • ui.dialog.js
Why do we need these? Well they are pretty much self explained. We need the core by default. We are making our message box draggable and resizable. And lastly we need the specific dialog component.

We also need to add the jquery-1.3.2.min.js and jquery.bgiframe.js.

<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
    <script type="text/javascript" src="js/ui.core.js"></script>
    <script type="text/javascript" src="js/ui.draggable.js"></script>
    <script type="text/javascript" src="js/ui.resizable.js"></script>
    <script type="text/javascript" src="js/ui.dialog.js"></script>
    <script type="text/javascript" src="js/jquery.bgiframe.js">
</script>

Now we are going to use built in CSS style for the dialog box.
<link type="text/css" href="ui.all.css" rel="stylesheet" />

These are the basic requirements to use the dialog box. Now that we are ready, lets roll.
The message box looks like this -




Actually we create the message box using the html tag <div> . An example -
<div id="dialog" title="here goes your title" style="visibility:hidden">
    <p>here goes your message</p>
</div>
This div is hidden so normally we cant see it when the page loads. Now our last task is to assign the jQuery event such that whenever a page loads the message pops up automatically.

This is done like this -
<script type="text/javascript">
    $(function() {
                    $("#dialog").css("visibility:visible");
        $("#dialog").dialog({
            bgiframe: true,
            height: 600,
            width: 1000,
            modal: true,
            buttons: {
                Ok: function() {
                    $(this).dialog('close');
                }
            }
        });
    }); 
</script>
The first line is the $(function () {}); When the page loads this function is called. So, all other code must reside with it.
the second line contains $("#dialog").css("visibility:visible"); The #dialog finds the element whose id is dialog (that is of course our message div we have created earlier). We now sets the CSS value to visible because now we want the user to see the message box.
The next line creates the dialog box along with height, width and buttons. If you want the message box to be modal (which is most of the cases is) we have to set it to true.

Next step -  just joking. All done. Just refresh your webpage. Amazing, isn't it?
If any question or suggestion please leave a comment. Thanks.