Add

Showing posts with label JQuery and CSS tips. Show all posts
Showing posts with label JQuery and CSS tips. Show all posts

Credit Card Validation Plugin in Jquery

Introduction


It's been a long time since my last post. In the last two months I was running through a hectic schedule, so could not publish anything here.

But this time I am here with my first ever JQuery Plugin and that's on Credit Card Validation.

While working with any payment gateway its an important thing to validate the correct credit card/debit card details. You may have developed an interface where the user has to give the credit card details like card no, cvv no, expiry date, name on the card. These fields need to be validated before processing towards the payment.

In order to validate the credit card details you may use the jquery or server side coding with the help of regex expressions, which is a time taking thing. So I thought of developing an efficient plugin which can create a nice looking interface along with the user friendly validations that can be consumed in any type of application. So here it is.

In this post we will see how this plugin works and how to use it in your application. You can download the plugin from the below link.

   Download Source Code Here

  Behind The Scene








**I have used bootstrap for design purpose, you can use it or not according to your project requirement.

Before entering into the plugin details lets know some basic things about the credit card number pattens.

The first digit in your credit-card number signifies the system:

    3 - travel/entertainment cards (such as American Express and Diners Club)
    4 - Visa
    5 - MasterCard
    6 - Discover Card

The structure of the card number varies by system. For example, American Express card numbers start with 37; Carte Blanche and Diners Club with 38.
  •  American Express - Digits three and four are type and currency, digits five through 11 are the account number, digits 12 through 14 are the card number within the account and digit 15 is a check digit.

  •  Visa - Digits two through six are the bank number, digits seven through 12 or seven through 15 are the account number and digit 13 or 16 is a check digit.

  • MasterCard - Digits two and three, two through four, two through five or two through six are the bank number (depending on whether digit two is a 1, 2, 3 or other). The digits after the bank number up through digit 15 are the account number, and digit 16 is a check digit.

(Courtesy: http://money.howstuffworks.com)

Lets get into the coding things. Ok first of all we will see the user interface and design it for enabling the user to provide his/her card details for validation and further proceedings.

I have used Bootstrap to get a UI like this, You can use it or else you can not according to your requirement.

This is how our UI is going to look like. Don't you guys like it ? please share your valuable comments below to modify it.
UI for CC Validation
Before we can start you need to download the plugin first. If you have not till now then download it from below.

Download Source Code

Once you download and extract it you will find the below javascript files in the js folder.
  • jquery-1.7.1.min.js
  • ccvalidate-tapan.min.js
We will be needing the ccvalidate-tapan.min.js file for our validation thing and you can add a latest JQuery to your project too.

 In the css folder you will find the below css files
  • bootstrap.css
  • Validation.css
Ok, Now lets jump into the coding part. Here is the HTML page how it looks like.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
    <link href="css/bootstrap.css" rel="stylesheet" />
    <link href="css/Validation.css" rel="stylesheet" />
    <script src="js/ccvalidate-tapan.min.js"></script>
    <script>
        $(document).ready(function () {
            // Initiate CC Validation
            InitiateValidation();

            // For check valid invalid details
            $("#btnValidate").click(function () {

                if (ValidateForm()) {
                    alert('You have entered valid details...');
                }
                else {
                    alert('You have entered invalid details/skipped some fields...');
                }
            });
        });

    </script>
</head>
<body>
    <div style="margin-top: 50px;" class="container">
        <div class="row">
            <div class="col-sm-5 col-xs-offset-3">
                <div class="well">

                    <div class="row">
                        <div class="col-sm-12">
                            <label class="col-sm-12 control-label">Enter Card No.</label>
                            <div class="col-sm-12">
                                <input placeholder="4587-7834-6735-1930" id="1" class="form-control" filtertype="CCNo">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-sm-8">
                            <label class="col-sm-12 control-label">Expiry Date (MM/YY)</label>
                            <div class="col-sm-12">
                                <input placeholder="12/20" id="3" class="form-control" filtertype="Date">
                            </div>
                        </div>
                        <div class="col-sm-4">
                            <label class="col-sm-12 control-label pull-right">CVV</label>
                            <div class="col-sm-12">
                                <input placeholder="454" id="3" class="form-control" filtertype="Number">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-sm-12">
                            <label class="col-sm-12 control-label">Name on Card</label>
                            <div class="col-sm-12">
                                <input placeholder="Tapan kumar" id="1" class="form-control" filtertype="CharacterAndSpace">
                            </div>
                        </div>
                    </div><br />
                    <div class="row">
                        <div class="col-sm-12">
                            <button id="btnValidate" class="btn btn-info col-sm-3 col-sm-offset-4 control-label">Submit</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

If you look into the above code you will find that I am using an attribute named filtertype for the input fields, which is responsible for the validation.

Here is the attribute values I have used for validating your card details.
  • Credit Card No : filtertype = "CCNo"
  • Expiry Date :  filtertype = "Date"
  • CVV No : filtertype = "Number"
  • Name on Card : filtertype = "CharacterAndSpace"

These attribute values are used into validate your card details and prevent user from inserting invalid entries in the input fields.
What you have to do is just to call 2 methods in JQuery in order to validate the card details. Find the script below.

    <script>
        $(document).ready(function () {
            // Initiate CC Validation
            InitiateValidation();

            // For check valid invalid details
            $("#btnValidate").click(function () {

                if (ValidateForm()) {
                    alert('You have entered valid details...');
                }
                else {
                    alert('You have entered invalid details/skipped some fields...');
                }
            });
        });

    </script>

The  InitiateValidation() method initiates the validation, and ValidateForm() method will return a boolean if the form is valid or not and you can perform your task accordingly. Here I am showing some alert if the details are correct or not in the click event of the submit button.

That's all for your validation to work out.

Plugin Features :

  • while inserting the card no it will automatically put a "-" in between 4 digits.
  • It will not allow you put anything except numbers in the card input field.
  • It will show your card type at the right side of the text box.
  • Max length of the CCNo field is 19(including the "-").
  • In the Date field you wont be able to put anything except numbers and the field will not accept the first two digits greater than 12 as these two digits indicates the month.
  • Max length of the Expiry Date field is 6(including the "/").
  • Now the CVV no field will accept only 3 digits.
  • Finally the Name on Card field will accept a name, which should be at least of 3-4 characters.
Happy Coding...



Applying Custom Styles To Default GridView Pagination

Introduction


This article will demonstrate you how to add some customize styles to your asp.net GridView paging. In case you are using the default paging functionality in GridView/ListView/DataGrid then you may need this thing to make your website little cool and pretty.

 

Behind The Scene


Lets take the below grid view for our example. Here we are giving a CssClass to the default pager named "gridView"
 <asp:GridView ID="grd_MyExample" runat="server" CssClass="grid" AllowPaging="True" 
   OnPageIndexChanging="grd_MySalesClaims_PageIndexChanging" GridLines="None" >
    <PagerStyle CssClass="gridView"/>
    <Columns>
     <asp:BoundField DataField="UserID" />
     <asp:BoundField DataField="UserName" />
    </Columns>
 </asp:GridView>

OK, when this GridView gets loaded in the web page we can find the pagination indices are coming inside a "tr". So what we have to do in order to give some customize styles to it ????

Lets check the below CSS...
        .gridView {
            background-color: #fff;
            padding: 2px;
            margin: 2% auto;
        }

            .gridView a {
               cursor: hand;
               font-family: Verdana;
               font-size: 12px;
               padding: 2px 6px;
               border: solid 1px #ddd;
               text-decoration: none !important;
               color: Black;
            }

                .gridView a:hover {
                   background-color: #5D88AC;
                   color: #fff;
                   font-family: verdana;
                   cursor: pointer;
                }

            .gridView span {
                background-color: #5D88AC;
                color: #fff;
                font-family: verdana;
                font-size: 14px;
                padding: 2px 6px;
            }

        table.grid tr.gridView td {
            padding: 0px;
        }
Oh that's cool,Now if you look into the GridView in your webpage you can find a nice looking pagination is coming under it.

In the above CSS we have given some style to the elements like "td","tr","a" those present inside the element with class "gridView".

That's it we have just applied some customizes styles to the ASP.NET GridView.

Happy Coding...

Responsive Navigation Bar In Twitter Bootstrap 3

Introduction

Now-a-days Its very important to make your website compatible with the mobile devices. In order to make it possible you need to figure out somethings by learning how to make responsive websites.

Bootstrap 3 gives you a powerful platform to make your website responsive and here I am showing a live demo of making a responsive navigation bar in Twitter Bootstrap 3.

First download the below style-sheet and the js file.
 You can download the source code here too.
 

Behind The Scene

OK, before we start this thing you must be a bit familiar with the Bootstrap things like classes, components etc. if you are not aware of this thing just have a look into this link;

Download Bootstrap and Learn

Let's take a html page first and add the below references.
 <head>   
     <link href="css/bootstrap.min.css" rel="stylesheet">
     <script src="js/bootstrap.min.js"></script>
     <meta name="viewport" content="width=device-width, intial-scale=1.0">
 </head>
* This meta is required to enable the responsive design( this example will work if you remove this meta too)

Now we will see how to design the carousel slider.

Creating The Navigation Bar


Use the below code to make a responsive navigation bar.
    <div class="container">
        <div class="navbar navbar-default navbar-fixed-top">
            <div class="navbar-header">
               <button class="btn btn-scuuess navbar-toggle"
                        data-toggle="collapse"
                        data-target=".navbar-collapse">
                    <span class="glyphicon glyphicon-chevron-down"></span>
               </button>
            </div>
            <div id="logo">
                <a href="#"><h4>Tapan Kumar</h4> </a>
            </div>
        
        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav navbar-right">
                <li class="nav active"><a href="#"> Home</a></li>
                <li class="nav"> <a href="#"> About</a></li>
                <li class="nav"><a href="#"> Blog</a></li>
                <li class="nav"><a href="#"> Article</a></li>
                <li class="nav"><a href="#"> Example</a></li>
                <li class="nav"><a href="#"> Contact</a></li>
            </ul>
        </div>
    </div>
  </div> 
In the above code we have given the div containing the navigation list a class named "navbar-collapse collapse", which tells the browser to hide the links (ul/li) in smaller screen resolutions.


And the button we have taken above the list inside the navbar-header div has two attributes named data-toggle which tells the browser that this is a toggle element and also has another attribute named data-target which tells the browser to show what and to hide what when user clicks on it.


The data-target is set to the class of the div, containing the navigation list.

Live demo




That's all, we have just designed a responsive navigation bar using Bootstrap 3.

Happy Coding...

How To Call A JavaScript Method From C#

Introduction

This is very silly thing but used very often. Calling a JavaScript Method to do something from code behind(C#) is not so difficult.

You may need this thing in order to show a custom alert using jQuery modal pop up, or for custom redirection when you are in an IFrame.

Behind The Scene


Recently I was stuck in some redirection problems. The senario is something like, I was in some iframe but after session out I need to go back to the login page. But the control in not in my hand as I am inside an iframe.
I tried a lot of things but what resulted me is reloading or rendering the page I was referring inside the iframe. But my purpose was to redirect the whole page to login page.
So I did this using JavaScript, and I need to call a JavaScript function form the C# code when session is out.
There are some way in which you can call a JavaScript function from code behind.

  // redirect user to home page.
  ScriptManager.RegisterStartupScript(this, GetType(), "load", "closeDocumentIFrame();", true);
 
*closeDocumentIFrame(); is the method written in the aspx page
  // redirect user to home page.
  ClientScript.RegisterStartupScript(GetType(), "Load", String.Format("<script type='text/javascript'>closeDocumentIFrame();</script>"));
 
*closeDocumentIFrame(); is the method written in the aspx page
  // redirect user to home page.
  ClientScript.RegisterStartupScript(GetType(), "Load", String.Format("<script type='text/javascript'>window.parent.location.href ='{0}' </script>", "http://www.google.com"));
 
You can too add the JavaScript code here instead of writing another method in page level.

Happy Coding...

Carousel Image Slider In Twitter Bootstrap 3

Introduction


Bootstrap 3 is a very powerful CSS framework that has the power to make the life of a web designer very very easy.

Image slider is a very important thing when web design comes to our mind. You definitely need this in your website to add some life to the inactive text contents in order to catch the attention of the user. Before the revolution brought by Bootstrap, we used to use different jQuery plugins to create image sliders. But after Bootstrap creating an image sliders made so easy for you like a piece of cake.

Bootstrap offers a lot many CSS classes, jQuery plugins. Here we will see how to create a carousel image slider using this Bootstrap 3.

First of all download the Bootstrap 3 files from here Download, and extract the zip file. All you need is the below tow files.

 

Behind The Scene


Once you downloaded  and extracted it from the above link, add a HTML page to the root folder. And give reference to the above said two files located in the JS and CSS folders respectively.
  <head>   
     <link href="css/bootstrap.min.css" rel="stylesheet">
     <script src="js/bootstrap.min.js"></script>
  </head>
Now we will see how to design the carousel slider.

Creating The Carousel Slider


Use the below code to create an impressive image slider.
 <div class="carousel slide" id="theCarousel" data-interval="3000">
    <div class="carousel-inner">
        <div class="item active">
            <img src="http://www.ansupalake.in/gallery/tapan%20kumar%201.JPG" alt="1" class="img-responsive" />                     
        </div>
        <div class="item ">
            <img src="http://www.ansupalake.in/gallery/tapan%20kumar%202.JPG" alt="2" class="img-responsive" />                    
        </div>
        <div class="item ">
            <img src="http://www.ansupalake.in/gallery/tapan%20kumar.JPG" alt="3" class="img-responsive" />                      
        </div>
    </div> 
 </div> 
*data-interval : This is the time interval in which you want to slide the images(here it is 3 sec).

The class "carousel slide"  tells bootstrap that this control contains a carousel image slider inside it. Then the div with class "carousel-inner" holds all the images you need to slide in the slider.

Inside the div with class "carousel-inner" put your image tags in separate divs with class "item", give the class "active" to the item you want to show first.

That's it you are just a step away to create the beautiful image slider. Just call the "carousel" plugin from jQuery in document.ready.
 <script type="text/javascript">
  (function () {
      $("#theCarousel").carousel();
   })();
 </script>
* "#theCarousel" is the id of the carousel div.

Here take a look how the simple carousel image slider looks like in jsfiddle.


Giving Indicators To The Carousel


You can add custom slider indicators also in the carousel. Just add a ordered list with class "carousel-indicators"
 <ol class="carousel-indicators">
    <li data-target="#theCarousel" data-slide-to="0" class="active"></li>
    <li data-target="#theCarousel" data-slide-to="1"></li>
    <li data-target="#theCarousel" data-slide-to="2"></li>
 </ol>
* "data-target" attribute holds the id of the carousel and "data-slide-to" attribute holds the slide number starting from 0
* add class "active" with respect to the active element of your slide.

Here take a look how the simple carousel image slider with indicators looks like in jsfiddle.


Giving Custom Navigation To The Carousel 


Now lets give a "Prev" and "Next" navigation to our carousel slider. You can do this by just adding two anchor tags, below the last item div.

You can give a span inside the anchor tag to show icons, the code is below.
 <a href="#theCarousel" class="carousel-control left" data-slide="prev">
     <span class="icon-prev"></span>
 </a>
 <a href="#theCarousel" class="carousel-control right" data-slide="next">
     <span class="icon-next"></span>
 </a>

* The anchor tag contains the ID of the carousel in the href attribute.
* The left and right navigation control have a class of "carousel-control left" and "carousel-control right" respectively.
* The "data-slide" attribute has a value of "prev" and "next" accordingly.

 Here take a look how the simple carousel image slider with navigation looks like in jsfiddle.


Giving Captions To The Carousel Slider


Here in this section we will give a custom captions to the individual slides. This is very simple to do. Just add  a div with class "carousel-caption" just below each image tag. And you are free to place whatever you want inside that div.

See the below code for this.
 <div class="carousel-caption">
     <h4 class="text-left">Resting In Style</h4>
     <p class="text-left">Hi Everybody what's going on.....</p>
 </div>
 Here take a look how the simple carousel image slider with captions looks like in jsfiddle.


Now you have seen how to make a beautiful carousel with indicators, navigations and captions in Bootstrap 3.

Happy Coding...

How To Check If Your Browser Supports HTML5 Or Not

Introduction


Recently while working on a video file integration in a website I got this interesting thing for you. As HTML5 supports your .mp4 video files and many more video files like .flv, .oog etc. But the main thing you need to sure about before integrating a video file is if your browser supports HTML5 or not.

If your browser does not support HTML5 then you can not play a .mp4 format in your website, so all you need is a flash video.

 

Behind The Scene


So my requirement was something like, I was asked to serve the user a flash video if his/her browser does not support HTML5 and .mp4 video if supports HTML5.

As you all of you know that there are many versions of IE till now those people are using, does not support HTML5. So this requirement is a genuine issue for all of us who are trying to integrate video files to their websites.

Let me clarify you if you have a HTML5 compatible browser then you just need 3 line of code to embed a .mp4 video to it in order to play it. See it below.
 <video width="320" height="240" controls>
 <source src="VideoFiles/movie.mp4" type="video/mp4">
  </video> 
Just put the above code to play a .mp4 file stored in the folder VideoFiles.

Now lets check for our main aim i.e HMTL5  compatibility.

Let's take a div inside your HTML code that contains both the .mp4 files and .swf files. Our main aim will be to hide one of them accordingly by considering the browser compatibility.
 <div>
 <object id="flashVideo" width="0" height="0" style="padding: 10px;">
     <embed width="320" height="240" src="videos/ansupalake.swf" style="margin-top: 10px;">
  </object>
   
 <video id="mp4Video"" width="320" height="240" controls>
      <source src="videos/ansupalake.mp4" type="video/mp4">
 </video> 
 </div>
 Now lets check in JavaScript regarding the compatibility.

 <script type="text/javascript">

    // Define the get_mime function
    var get_mime = function(filetype){
    var mimetype = '';
    var media_container = 'video';

    switch(filetype){
     case 'mp4':
      mimetype = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
      break;
     case 'ogg':
      mimetype = 'video/ogg; codecs="theora, vorbis"';
      break;
     case 'webm':
      mimetype = 'video/webm; codecs="vp8, vorbis"';
      break;
     case 'mp3':
      mimetype = 'audio/mpeg';
      media_container = 'audio';
      break;
    }
    
    return {'mimetype':mimetype,'container':media_container};  
    };

    // Check to see if the browser can render the file type
    // using HTML5
    var supports_media = function(mimetype, container) {
    var elem = document.createElement(container);
    
    if(typeof elem.canPlayType == 'function'){
     var playable = elem.canPlayType(mimetype);
     if((playable.toLowerCase() == 'maybe')||(playable.toLowerCase() == 'probably')){
      return true;
     }
    }
    return false;
    };

    // When the DOM has loaded check the file extension of each media link
    // and serve up appropriate media player
    $(document).ready(function(){
    
        /* Use the below three line to get the extension of a file dynamically. Here It gets the attribute "href" of a hyperlink
         and then extension            
          var path = $('#videoFile').attr('href');
          var extension = path.substring(path.lastIndexOf('.') + 1);
          var extension_info = get_mime(extension);
        */
    
        // Now get the MIME type for type mp4 files.
        var extension_info = get_mime('mp4');
    
        if(supports_media(extension_info.mimetype, extension_info.container))
                  {  
                    // Serve up an HTML5 Media Player and controls
                    serve_html5();
                  }
                  else
                  {
              // Serve up a flash based video for browsers that.
              serve_flash();
           } 
          });    

    function serve_flash(){
    $('#mp4Video').hide();
    }
    
    function serve_html5(){
    $('#flashVideo').hide();
    }
    
</script>
Let me explain what I have done in the above code. First in the document.ready function I am trying to get the MIME type of the video you want to play. ( here I am using a hard coded value .mp4, you can use the commented code to get the file extension from the HTML element dynamically )

OK, after getting the MIME type we are calling the supports_media method to check if it can create a video element in the DOM dynamically or not.

If it was able to create then we are sure that your browser supports HTML5 otherwise not. And exactly my code serves this way. It returns True if element was created successfully else returns you False . And then server you Flash or HTML5 accordingly by hiding the elements we have created before inside the div first.

Hope this article will help you to check if your browser supports HTML5 or not and to serve video files accordingly.

Happy Coding...

How To Change The Src Attribute Of An Image Tag In Jquery

Introduction


While walking through web design, you may wonder for sometime that how to change the a image source on clicking on it. It is a basic requirement when there is something you want to hide on clicking the image, and to unhidden by clicking on it again.

Let me explain this in a simple way;
There is a div which has a "+" image and another div below it. Our goal is to show that div when we click on the "+" image and to change the image from "+" to  "-"
Again  when we click on the "-" image then the div will be hidden with the image changed from  "-" to "+".
Now I think the requirement is clear. Lets acheive this with Jquery.

Here is a screen shot how it will look like
Image On Off
   Download Source Code Here
   

Behind The Scene


Lets take a div with class headerList and an image tag inside it like below
        <div class="headerList">
            <img src="image/PLUS.gif" alt="xyz" class="ImageOnOff" style="cursor: pointer" />
            Header Section 1
        </div>
        <div class="childGrd">
            Body Part 1
        </div>

        <div class="headerList">
            <img src="image/PLUS.gif" alt="xyz" class="ImageOnOff" style="cursor: pointer" />
            Header Section 2
        </div>
        <div class="childGrd">
            Body Part 2
        </div>
From the above design you can see that there are two identical divs those have the same structure. And this will look like below.
Now, you can predict what I want to show you here. Yes I am going to click the "+" sign and that will open the slightly green div ( shown in the top screen shot ). Along with the showing the div the "+" sign will be converted to "-".

To acheive this you need to put the below JQuery code in your page.
<script type="text/javascript">

  $(function () {
   //Hide the green divs initially
   var id =  $(".headerList").closest('div');
   $(id).next('div.childGrd').hide();
    });
    // Change the image source when the image is clicked
    $("img.ImageOnOff").live('click', function () {
    
   if ($(this).attr("src").toString().indexOf('PLUS.gif') != -1) 
     {
    this.src = this.src.replace("PLUS.gif", "MINUS.gif");
     }
     else 
     {
    this.src = this.src.replace("MINUS.gif", "PLUS.gif");
     }
   
   // Toggle the green div when the image is clicked
   var currentRow = $(this).closest('div');
   var tr = $(currentRow).next('div');
   $(tr).toggle();
  }); 
 
 </script>
The above jquery code explains how to replace the image source on the click of the image and how to find the next div which has to be hidden.

Happy Coding...

How To Make Dynamic Versioning For CSS and JS Files

Introduction

 

If you are developing a web application in HTML and CSS or any other technology, and you are using some external CSS or JS files, you might notice one thing that in some cases if you made any changes to your existing .css or .js files then the browsers are not reflecting the changes immediately.

What happens in that case is that the browser do not download a fresh copy of the latest version of the .css and .js files, instead it uses those files stored in your local cache. As a result the changes you made recently are not visible to you.

Behind The Scene

 

In this case if you want your results to be effective in your browser then you may need to refresh your browser or you may need to clear the cache of your browser so that it can download a fresh copy from the server. Or else there is a simple way to achieve this.

This is a very common problem in day to day codding life. Here is a simple way that explains how to fool around the browser and force it to download a fresh content of the .css or .js file.

Below is a stylesheet which has a source file "style.css" that end with a query string like thing "?v=1.1".
 <link rel="stylesheet" href="style.css?v=1.1"> 
The above case when you load the web page the browser will treat "style.css"  as a different file along with "?v=1.1". Hence the browser is forced to download a fresh copy if the stylesheet or the script file.

Dynamically Add Version to the URL:

If you want to do this versioning in a dynamic way then you can achieve this by using the config file in asp.net.

Let's say you are using a single style.css file in multiple locations, then there will be a bit problem when you change something in the file and forget the locations where the file is being used. There you can not add the versioning query string manually.

In this case you need a dynamic way to do this and here I achieved this using the config file in asp.net.

Just add a key inside the appsettings of your config file as below.
 <appSettings>
    <add key="Version" value="1.1"/>
 </appSettings>
Now in the page where the .css or .js files are being used, append the below code to the "src" attribute.
 <script src="Scripts/ModalPopUp.js?v=<%= System.Configuration.ConfigurationManager.AppSettings["Version"] %>" type="text/javascript"></script>
This will automatically append the query string "v=1.1" to the "src"  attribute of the link. And in future if you change anything in the .css or .js file then no need to find out all the locations to add versions, just change the version in the config file and your work is finished. You just make the browser fool to download a fresh copy.

Happy Coding...

Conditional CSS For IE ( Internet Explorer )

Introduction

Internet Explorer, the most used browser world wide. But as a developer we all are well know about the styling issues with this browser. Sometimes we got some CSS that may be working perfectly in Mozilla, Chrome and Safari but not in Internet Explorer.

At that very moment we need to check the browser and apply the styles accordingly. Here I will state a simple way to solve this issue using conditional css tricks. One thing this CSS trick will only work for IE (Internet Explorer)

Behind The Scene

If the styling issue is only with the IE then I got a very special and easy solution for this. That is called Conditional CSS. If the issue is with all other browsers then you may need to check the browser using JavaScript. Check my article for this. ( Check Browser in JavaScript )

Here is the conditional CSS. 

     
 <!--[if IE]>
 According to the conditional comment this is IE<br />
 <![endif]-->
 <!--[if IE 6]>
 According to the conditional comment this is IE 6<br />
 <![endif]-->
 <!--[if IE 7]>
 According to the conditional comment this is IE 7<br />
 <![endif]-->
 <!--[if IE 8]>
 According to the conditional comment this is IE 8<br />
 <![endif]-->
 <!--[if IE 9]>
 According to the conditional comment this is IE 9<br />
 <![endif]-->
 <!--[if gte IE 8]>
 According to the conditional comment this is IE 8 or higher<br />
 <![endif]-->
 <!--[if lt IE 9]>
 According to the conditional comment this is IE lower than 9<br />
 <![endif]-->
 <!--[if lte IE 7]>
 According to the conditional comment this is IE lower or equal to 7<br />
 <![endif]-->
 <!--[if gt IE 6]>
 According to the conditional comment this is IE greater than 6<br />
 <![endif]-->
 <!--[if !IE]> -->
 According to the conditional comment this is not IE<br />
 <!-- <![endif]-->


The above trick is the conditional css trick. Let me explain a bit about this.

<!--[if IE]> this tag will check if the browser is IE or not and the block inside the start and end tag will be executed only for IE. You can also check for the version of the IE browser like above. and put your CSS, Script, HTML or whatever you want to show in IE.


     
  <!--[if IE]>
         Put your code block CSS/Script/HTML for IE 
  <![endif]-->



My problem was with some CSS in IE8 so I added the below block for IE8.

     
  <!--[if IE 8]>
         <style type="text/css">
                   h1, h4, h5
                     {
                       margin: 0px;
                       padding-top: 5px;
                       padding-bottom: 5px;
                     }
               </style>
 <![endif]-->



The above conditional css will be applied for the h1, h4, and h5 tags when the browser is IE 8 otherwise not.

I hope this will be a bit helpful for you, when you face problems regarding cross browser compatibility of designs in IE.

Happy Coding...

How To Check Browser In JavaScript

Introduction


Its a very common thing as we know, how to check browser in Jquery. But he point is when we are going to do this in Javascript we will find a bit problem there as there is no inbuilt method to get you the exact browser. Here I will explain how to achieve this and what is the advantage of using Javascript instead of Jquery.



Behind The Scene


First lets focus why should we go for using Javascript instead of using Jquery where as its very simple to use the latter.

The point is that while using the Jquery you need to load the manifest file for each and every time you load the page. That is the "$" will need the jquery file so the browser downloads the whole file every time by reducing the performance of the site. Hence its always advisable that try avoiding Jquery when the work can be done through Javascript.

Recently I have a requirement of checking the browser so I did this in Jquery but when I go to my deployment manager to deployment manager for deploying this he denied me by telling me that for this small thing we don't need to load the whole Jquery manifest file. And advice me to do it in Javascript. Finally I got a way to do this in Javascript.

Javascript provides a object called "navigator" that gives the visitors browser's information.

The information from the navigator object can often be misleading, and should not be used to detect browser versions because:
  •     The navigator data can be changed by the browser owner
  •     Some browsers misidentify themselves to bypass site tests
  •     Browsers cannot report new operating systems, released later than the browser

Here is the code you can use this to check in cross browser, I have found this is giving the browser appCodeName "Mozila" in all my browsers and some different values. I mean if you want to check the browser name only you can not do this by using a particular object.

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    
</head>
<body>
<div id="example"></div>

<script>

txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";
txt+= "<p>User-agent language: " + navigator.systemLanguage + "</p>";

document.getElementById("example").innerHTML=txt;

</script>
</body>
</html>
Here I found a way to do this in javascript. And below is the code for that
var BrowserDetect = {
 init: function () {
  this.browser = this.searchString(this.dataBrowser) ||
                                                       "An unknown browser";
  this.version = this.searchVersion(navigator.userAgent)
   || this.searchVersion(navigator.appVersion)
   || "an unknown version";
  this.OS = this.searchString(this.dataOS) || "an unknown OS";
 },
 searchString: function (data) {
  for (var i=0;i<data.length;i++) {
   var dataString = data[i].string;
   var dataProp = data[i].prop;
   this.versionSearchString = data[i].versionSearch ||
                                                             data[i].identity;
   if (dataString) {
    if (dataString.indexOf(data[i].subString) != -1)
     return data[i].identity;
   }
   else if (dataProp)
    return data[i].identity;
  }
 },
 searchVersion: function (dataString) {
  var index = dataString.indexOf(this.versionSearchString);
  if (index == -1) return;
  return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
 },
 dataBrowser: [
  {
   string: navigator.userAgent,
   subString: "Chrome",
   identity: "Chrome"
  },
  {  string: navigator.userAgent,
   subString: "OmniWeb",
   versionSearch: "OmniWeb/",
   identity: "OmniWeb"
  },
  {
   string: navigator.vendor,
   subString: "Apple",
   identity: "Safari",
   versionSearch: "Version"
  },
  {
   prop: window.opera,
   identity: "Opera",
   versionSearch: "Version"
  },
  {
   string: navigator.vendor,
   subString: "iCab",
   identity: "iCab"
  },
  {
   string: navigator.vendor,
   subString: "KDE",
   identity: "Konqueror"
  },
  {
   string: navigator.userAgent,
   subString: "Firefox",
   identity: "Firefox"
  },
  {
   string: navigator.vendor,
   subString: "Camino",
   identity: "Camino"
  },
  {  // for newer Netscapes (6+)
   string: navigator.userAgent,
   subString: "Netscape",
   identity: "Netscape"
  },
  {
   string: navigator.userAgent,
   subString: "MSIE",
   identity: "Explorer",
   versionSearch: "MSIE"
  },
  {
   string: navigator.userAgent,
   subString: "Gecko",
   identity: "Mozilla",
   versionSearch: "rv"
  },
  {   // for older Netscapes (4-)
   string: navigator.userAgent,
   subString: "Mozilla",
   identity: "Netscape",
   versionSearch: "Mozilla"
  }
 ],
 dataOS : [
  {
   string: navigator.platform,
   subString: "Win",
   identity: "Windows"
  },
  {
   string: navigator.platform,
   subString: "Mac",
   identity: "Mac"
  },
  {
      string: navigator.userAgent,
      subString: "iPhone",
      identity: "iPhone/iPod"
     },
  {
   string: navigator.platform,
   subString: "Linux",
   identity: "Linux"
  }
 ]

};
BrowserDetect.init();

Use this method in your page and it will return you the browser name by calling "BrowserDetect.browser" object.

You can download the sample code and check this by opening it on different browsers it will show you an alert containing the browser name, that you are using.

Happy Coding...

Simple Image Slider Using JQuery and CSS

Introduction


Creating an image slider is one of the most important thing one needs while developing a website. You may need to implement image slider for many reasons, here I will show you the simplest example of creating a image slider using only JQuery and CSS. This is the simplest way to implement this instead of using others JQuery library for Image Slider



Behind The Scene


Here I am taking a simple html web page in which I will place a single div containing your images, those are for slider. Give an id to the div that will be used in the JQuery function we will write for the slider.
 <div id="s_show" class="divMain" style="margin-top: 5px; height: 155px;">
   <img class=" active" width="100%" src="images/home-1.jpg" style="opacity: 1;">
   <img class=" " width="100%" src="images/home-2.jpg" style="opacity: 1;">
   <img class=" " width="100%" src="images/home-4.jpg" style="opacity: 1;">
 </div>
Now add a floder to th root folder and named it as "images"  inside this folder put the images you want to show, and the JQuery files "jquery-1.4.1.js", "jquery-1.4.1.min.js".

Now add the following line of styles to the page .
 <style type="text/css">
 #s_show {
  position: relative;
  height: 350px;
 }
 #s_show IMG{
  position: absolute;
  top: -4px;
  left: 0px;
  z-index: 8;
  opacity: 0.0;
  height: 200px;
  width: 100%;
 }
 #s_show IMG.active{
  z-index: 10;
  opacity: 1.0;
 }
 #s_show IMG.last-active{
  z-index: 9;
 }
 .divMain{
  width: 721.2px;
  margin: 40px auto 0 auto;
  padding: 20px 35px;
  background: #FFFFFF;
 }
 .section{
  border: 1px groove #9FD0F6;
  border-right-width: 5px;
  width: 255px;
  float: left;
  background: #FFFFFF;
  margin-right: 5px;
  height: 155px;
 } 
</style> 
Fine, now add the below given script to the head section of the web page. And also add the "jquery-1.4.1.js" and "jquery-1.4.1.min.js" files to the header section of the page.

<script src="images/jquery-1.4.1.js" type="text/javascript"></script>
<script src="images/jquery-1.4.1.min.js" type="text/javascript"></script>

<script type="text/javascript">
function slideShow() {
 var $active = $('#s_show IMG.active');
 if ($active.length == 0) $active = $('#s_show IMG:last');
 var $next = $active.next().length ? $active.next()
 : $('#s_show IMG:first');
 $active.addClass('last-active');
 $next.css({ opacity: 0.0 })
 .addClass('active')
 .animate({ opacity: 1.0 }, 1000, function () {
 $active.removeClass('active last-active');
 });
 }
 
$(function () {
 setInterval("slideShow()", 3000);
});
</script> 
Now you are done with your own image slider. For complete project download it form the above link and just run it.

Happy Coding...