Showing posts with label jQuery Tips. Show all posts
Showing posts with label jQuery Tips. Show all posts

Tuesday, August 26, 2014

How to serialize ASP.NET web form using jQuery

In this post, find how to serialize ASP.NET web form using jQuery. jQuery provides a very useful function jQuery.serialize() which encodes a set of form elements as a string.

What is serialize and why do we need?


Serialize is a way to combine your form values and create a single string which then can be used to send to server for ajax request. It is useful when your form is huge and you need to post all the form input value to server using ajax. Creating such string manually is not desired. Serialize can help you with this.

Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked.

How to use it?


Consider a following form with 3 input controls with a submit button.
<form action="#" id="form1">
     First name: <input type="text" name="first name" /><br />
     Last name: <input type="text" name="last name" /><br />
     Email: <input type="text" name="email" /><br />
     <input type="submit" value="send" id="btnSubmit" />
</form>
So when we serialize this form, so following serialize string is returned using "$("#form1").serialize();"
"first+name=jQuery&last+name=byexample&email=jquerybyexample%40gmail.com"

You can easily include particular set of controls while serializing the form. For example, you want to include only input controls not select controls.
function SerializeForm()
{
   var sValue = $("#form1")
               .find("input")
               .serialize();
   return sValue ;
}
Above code will only serialize input controls only, ignoring all other controls.

What about ASP.NET Webform?


With ASP.NET Webform, there is an issue. As to maintain states between postback, ASP.NET adds two extra input controls with ID "__VIEWSTATE" and "__EVENTVALIDATION". And we don't want to serialize these two controls input. We need to ignore them otherwise your serialize string will break and code will fail. So use ".not()" selector to ignore these 2 controls.
function SerializeForm()
{
   var sValue = $("#form1")
               .find("input,textarea,select")
               .not("#__VIEWSTATE,#__EVENTVALIDATION")
               .serialize();
   return sValue ;
}
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, June 10, 2014

Detect IE11 using JavaScript/jQuery

In this post, find JavaScript/jQuery code to detect IE 11. Your old code detect IE browser either using navigator.userAgent or $.browser.msie will not work for IE 11 as the User Agent string for IE 11 is changed.

Previously I had posted about Detect Browsers using jQuery, but with the release of jQuery 1.9 $.browser feature was removed. But to support legacy code, they have released jQuery Migrate plugin to detect deprecated and removed features, or to restore old features for those sticky situations where you need old code to run with new jQuery. You can read more about How to migrate older jQuery code to jQuery 1.9+

You may also like:
The user agent string for IE11 on Windows 8.1 is,
Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko
And if you compare with earlier version of IE then you will find the "MSIE" token is no longer present. For the earlier version of IE, "MSIE" token was present. Take a look at IE10 user agent string.
Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)
So the code to find index of "MSIE" in navigator.userAgent will not work for IE11.
var sAgent = window.navigator.userAgent;
var Idx= sAgent.indexOf("MSIE");
So to detect IE11, all you need is to look for "Trident/7.0" in user agent string. Here is updated code to detect all versions of IE including IE 11.
function GetIEVersion() {
  var sAgent = window.navigator.userAgent;
  var Idx = sAgent.indexOf("MSIE");

  // If IE, return version number.
  if (Idx > 0) 
    return parseInt(sAgent.substring(Idx+ 5, sAgent.indexOf(".", Idx)));

  // If IE 11 then look for Updated user agent string.
  else if (!!navigator.userAgent.match(/Trident\/7\./)) 
    return 11;

  else
    return 0; //It is not IE
}

if (GetIEVersion() > 0) 
   alert("This is IE " + GetIEVersion());
else 
   alert("This is not IE.");
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, January 7, 2014

How to restore CSS styles using jQuery

To assign inline css to any DOM element, we can jQuery ".css()" method to define it. Like,
$("#dvText").css('color','#FF0000');
And if you need to remove the color again, then you can use the same css method to remove it. Like,
$("#dvText").css('color','');
The above method to remove/restore the style is fine, when you have defined a single inline css class. If you have defined multiple CSS styles like,
$(document).ready(function(){
  $("#dvText").css('background-color','#FFFF00');
  $("#dvText").css('color','#FF0000');
  $("#dvText").css('font-family','Arial');
  $("#dvText").css('font-size','18pt');
});
Or using CSS method to combine multiple CSS styles.
$("#dvText").css({
  'background-color':'#FFFF00',
  'color':'#FF0000',
  'font-family':'Arial',
  'font-size':'18pt'})
In this case, you need to write same number of statement to remove/restore all the CSS styles which defined earlier. Is there any simple and slick way to do this?

Yes, there is. But first understand what actually .css() method does. When .css() method is used, it defines a style attribute to the DOM element. For example,
$("#dvText").css('color','#FF0000');
will be equivalent to:
<div style="color:#FF0000;">...</div>
So, to remove/restore all the defined style attribute, all you need to do is to remove style attribute which you can do via "removeAttr()" method.
$("#dvText").removeAttr("style") ;
Read more...

Thursday, October 3, 2013

jQuery - Correct way to check if object is null or Empty

Yesterday, I ran into a interesting and frustrating situation where for couple of minutes I was not able to find out what's wrong with my code. But I learned something new. Let me first give you an idea about what I was working on. I was creating a function, which first checks of div element object. If not found, then create a new div element and insert in DOM otherwise just update the html of div.

Related Post:

Below is the jQuery code.
$(document).ready(function () {
    function UpdateHTML() 
    {
        var $dvElement = $('#dvElement');
        if (!$dvElement) 
        {
            $("<div />", {
                id: 'dvElement',
                html: 'Added Just now'
            }).appendTo('body');
        } 
        else 
            $dvElement.html('Updated HTML');
    }
});
When this function is called, it does nothing. In the first call, it should create a div but it was not. When I debugged, I found that it is always going in else part of the condition. The condition (!$dvElement) always returning false. Wooo..Confused...
Every time when we pass a selector to jQuery function, it will always return a jQuery object. So whether the div exist or not, an object is returned. And when we test the jQuery object inside if statement, it will always be TRUE.

To fix the above code, we need to find out whether the object is empty. And there are 2 ways to fix this.
  • length property: Returns number of elements in object
  • $.isEmptyObject(Object): Returns true if the object doesn’t define any methods or properties.
So fix is,
$(document).ready(function () {
    function UpdateHTML() 
    {
        var $dvElement = $('#dvElement');
        if (!$dvElement.length)  // OR !$.isEmptyObject($dvElement)
        {
            $("<div />", {
                id: 'dvElement',
                html: 'Added Just now'
            }).appendTo('body');
        } 
        else 
            $dvElement.html('Updated HTML');
    }
});
So always use .length or $.isEmptyObject() function to find out whether object is empty, null or has some elements.

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, October 1, 2013

jQuery code not working - A Daily Battle

Developers life is full of various code battles and "jQuery is not working" or "jQuery code is not working" is a just another daily battle which they have to fight against while working with jQuery. The message "jQuery is not working" itself defines its pain saying "Oh!!! there is something buggy in your code and that is stopping me from working". So in this post, we will see some basic strategies to win this "Daily Battle".


Earlier I had posted about Common jQuery Mistakes, Various reasons and solutions of jQuery is not defined error and series of articles on jQuery Mobile which you may find helpful to read.. Okay, Lets begin...

STRATEGY No. 1 : Check for jQuery Reference

The first strategy is to ensure that you have included the reference of jQuery library and That too at correct place. It has to before your jQuery code.
<script type="text/javascript" language="javascript">
  $(document).ready(function() {
      //Your jQuery code goes here....
 });
</script>

<script type="text/javascript" src="Script/jquery-1.9.2.min.js"></script>
So with this code, you are ready for your "Daily Battle", as the reference of the jQuery library is after the code.

Another important thing which matters a lot is order of your scripts. For example, if you are using jQuery along with jQuery UI, first include jQuery and then jQuery UI library.
<script type="text/javascript" src="Script/jquery-1.9.2.min.js"></script>
<script type="text/javascript" src="Script/jquery-ui-1.8.18.min.js"></script>
Same is true while using jQuery plugins.

STRATEGY No. 2 : Check Your Selectors

The second strategy is to find out whether "Wrong Element ID or CSS Class Name" is not used. This is a very common mistake developers do while writing code. This happens because developers believe that they can never go run with this. As they say "Confidence is good but over-confidence is bad".

Another common cause is to mix up "#" (hash) and "." (dot). Remember, "#" is used to select elements by ID and "." is used to select elements by css class name. Many times developer mixes these two and get ready for "Daily Battle". So make sure that your selectors are correct.

STRATEGY No. 3 : Check for Comma, Semi-colon, Brackets and Syntax

When you write jQuery code, you will find comma, quotes, semi-colon and brackets everywhere. Without the proper/correct use of these characters, your jQuery code is not going to love you back. So make sure that all these character are in place.

Another common mistake which every developer does, not intentionally though is incorrect syntax. Sometimes due to hurry or time limit, developers may ignore to check syntax which may lead to "Daily Battle". So make sure your syntax is correct.

STRATEGY No. 4 : Check for jQuery Version

jQuery team is continuously updating this library for making things fast and include new things. And they come up with newer version. Due to excitement of new release and eagerness to use new functionality, developers sometime include the new jQuery version without checking for old code compatibility.

For example, $.browser property to check for browser was removed in jQuery 1.9. And if you are using $.browser in your code and you have updated your code to jQuery 1.9, then your old code is going to break. Your Lead/ Project Manger/ Client will give you a kick and you are ready for your "Daily Battle".

So before updating to newer/latest version, check the release log on jQuery website to find out if any functionality is removed or deprecated in newer release. And always remember to test your old code against the new release.

STRATEGY No. 5 : Check for Conflict

Conflict happens. It happens everywhere. Well, lets admit it that "Nobody likes Conflict" and same is true for jQuery. It also hates conflicts. But conflicts with whom? Well, remember jQuery is not the ONLY client side library which exists in this world. There are many other competitors like prototype, mootools, YUI etc. And when there is competition, there is conflict of interest.

These libraries also use $() as their global function and to define variables. This situation creates conflict as $() is used by jQuery and other libraries as their global function. And you are ready for your "Daily Battle".

So we need conflict resolution. And to resolve conflict, jQuery has jQuery.noConflict().
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
     jQuery.noConflict();
     // Use jQuery via jQuery(...)
     jQuery(document).ready(function(){
       jQuery("div").hide();
     });  
     // Use Prototype with $(...), etc.
     $('someid').hide();
</script>

The above mentioned strategies are nothing, but just a checklist which you can always follow when your "jQuery code is not working". If you have anything to add in this, please include them in comments and share with the world.

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, August 20, 2013

jQuery - Page Redirect after X seconds wait

You must have come across any website which uses a webpage with some annoying advertisement and a message that says "You will be redirected to actual page after X seconds". This can be easily implemented with jQuery. In this post, find jQuery code to redirect user to another webpage after specific time interval or few seconds.

Related Post:
The below jQuery code uses JavaScript setInterval which executes a function, over and over again, at specified time intervals. So all is required is to set the setInterval as 1 second and then minus the counter from actual time interval. When it reach to zero second , simply redirect to specific path.
$(document).ready(function () {
   window.setInterval(function () {
      var iTimeRemaining = $("#spnSeconds").html();
      iTimeRemaining = eval(iTimeRemaining);
      if (iTimeRemaining == 0) {
         window.location.href = "http://jquerybyexample.blogspot.com/";
      }
      else {
         $("#spnSeconds").html(iTimeRemaining - 1);
      }
  }, 1000);
});
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Thursday, July 25, 2013

Difference Between jQuery().each() and jQuery.each()

jQuery has 2 different methods jQuery().each() (Also written as "$.each()") and jQuery.each(). Both the methods are similar in nature used for iteration or looping but the differ only at the level where they are used.

jQuery.each(): is used to iterate, exclusively, over a jQuery object. When called it iterates over the DOM elements that are part of the jQuery object.

$.each(): function can be used to iterate over any collection, whether it is an object or an array.

Related Post:
First, let see how jQuery.each() works. To work with this function, you always need to pass a selector on which iteration needs to be performed. Consider the following HTML,
<ul>
    <li>foo</li>
    <li>bar</li>
</ul>
Now below jQuery code, will select all "li" elements and loop through each of the item and logs its index and text.
$( "li" ).each(function( index ) {
  console.log( index + ": " + $(this).text() );
});
On the other side, $.each() is used to iterate through an object or array collection. See below jQuery code.
var obj = { one:1, two:2, three:3, four:4, five:5 };
$.each( obj, function( key, value ) {
  alert( key + ": " + value );
});
Got the idea about the difference. But you can also make $.each() function to make it similar to jQuery.each(). All you need to do is to instead of object or array, you can pass DOM collection to achieve the same result. See below jQuery code.
$.each($( "li" ), function( index, value ) {
  console.log( index + ": " + $(this).text() );
});
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Monday, July 22, 2013

jQuery: Select all readonly input type textbox

In this short post, find jQuery code to select all readonly input type textboxes present on the page.
$(function(){
    $(":input[type=text][readonly='readonly']").val("");
});
However, if you have single readonly textbox element, then select it using its ID. And if you want to exclude all readonly input type textboxes from selection, then use below jQuery code.
$(function(){
    $(":input[type=text]:not([readonly='readonly'])").val("");
});
The only difference is that ":not" selector is used to exclude readonly input type elements.

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Thursday, July 4, 2013

jQuery: How to Strip/Remove HTML tags

In this short post, find jQuery code to strip/remove HTML tags. To remove HTML tags, use text() function which returns only the text content and ignores the HTML portion.
console.log($('#dvTest').text());
You can also strip/remove HTML tags from any variable as well as text() is jQuery function, so the variable needs to be converted into a jQuery object so that text() can be used.
var str = '<div>Sample <u>HTML</u> <b>Text</b> with <i>tags</i></div>';
console.log($(str).text());
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Friday, June 21, 2013

Use protocol less URL for referencing jQuery

Learnt something new today and thought of sharing. Most of us, include the reference of jQuery library (if Google CDN is used) like this,
http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
As you can see it is using HTTP protocol. The advantage of Google CDN files are cached up to one year which means that your users may not need to download jQuery at all. But when you move from HTTP to HTTPS pages, then you need to make sure that you are using https protocol for referencing jQuery as pages served via SSL should contain no references to content served through unencrypted connections.

Related Post:
And take a note that content served via SSL are not cacheable. Browsers will simply ignore content served over SSL for caching. So you need to make sure that if you are moving from HTTP to HTTPS url, use correct protocol for referencing jQuery library as well.

The better approach would be to use "protocol-less" URL.
//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
It looks strange and initially I also felt the same but "protocol-less" URL is the best way to reference third party content that’s available via both HTTP and HTTPS. When a URL’s protocol is omitted, the browser uses the underlying document’s protocol instead.

Thus, using the protocol-less URL allows a single script reference to adapt itself to what’s most optimal: HTTP and it’s full caching support on HTTP pages, and HTTPS on secured pages so that your users aren't confronted with a mixed content warning.

Must Read:
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Thursday, June 20, 2013

Ignored powerful shortcuts of jQuery

Many developers ignore shortcuts and power of jQuery and I myself being a victim of some of the useful, handy but yet ignored shortcuts of jQuery. These are not some advance or complex shortcuts but I guess these are used a lot.

Consider, below jQuery code lines.
$("#elm").css("display", "none"); //Line 1
$("#elm").css("display", ""); //Line 2
$("#elm").html(""); //Line 3
Above code lines are very common but its unfortunate because some faster and more readable shortcuts available, yet ignored. Find below jQuery code lines that does the exactly same thing but these are more readable and fast.
$("#elm").hide(); //Line 1
$("#elm").show(); //Line 2
$("#elm").empty(); //Line 3
Related Post: There are many more examples which you can find in your code. For example, to add CSS Class to any element
$("#elm").prop("class", "cssClass");
where the better approach would be,
$("#elm").addClass("cssClass");
Another example is of setting height and width,
$("#elm").css("height", "100px"); //Line 1
$("#elm").css("width", "100px"); //Line 2
using in-built jQuery functions,
$("#elm").height(100); //Line 1
$("#elm").width(100); //Line 2
Another common situation is of toggling (show/hide) of element. For example,
if($("#elm").is(":visible")) 
    $("#elm").css("display", "none");
else 
    $("#elm").css("display", "");
where the better approach is,
$("#elm").toggle();
You can find many such situation where in-built jQuery functions can be used. Hope you find this useful and if you are also ignoring these shortcuts, then you need to move on...

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, June 18, 2013

jQuery to redirect page after specific time interval

You must have come across any website which uses a webpage with some annoying advertisement and a message that says "You will be redirected to actual page after X seconds". This can be easily implemented with jQuery. In this post, find jQuery code to redirect user to another webpage after specific time interval or few seconds.

The below jQuery code uses JavaScript setInterval which executes a function, over and over again, at specified time intervals. So all is required is to set the setInterval as 1 second and then minus the counter from actual time interval. When it reach to zero second , simply redirect to specific path.

Related Post:
$(document).ready(function () {
   window.setInterval(function () {
      var iTimeRemaining = $("#spnSeconds").html();
      iTimeRemaining = eval(iTimeRemaining);
      if (iTimeRemaining == 0) {
         window.location.href = "http://jquerybyexample.blogspot.com/";
      }
      else {
         $("#spnSeconds").html(iTimeRemaining - 1);
      }
  }, 1000);
});
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Thursday, June 13, 2013

Check for '#' hash in URL using jQuery

In this short post, find jQuery code to check if URL contains "#" (hash) or not. This can be checked via location.hash property provided by JavaScript and same can be used in jQuery.
$(document).ready(function(){
    if(window.location.hash) {
      // # exists in URL
    } 
    else {
       // No # in URL.
    }
});
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Wednesday, June 5, 2013

jQuery .end() and Chaining

Before you go further, I assume that you know What is chaining in context of jQuery? If not, then first read "What is Chaining in jQuery?". To summarize Chaining in jQuery means to connect multiple functions, events on selectors. Main advantage of using chaining is that it makes code look clean and gives better performance. You should make a habit of using chaining.

Related Post:

You will find that chaining is very easy to implement and indeed it is. But consider a scenario, where in a <div> element, find all <p> and <span> elements and assign background color to them. Below jQuery code will exactly do the needful.
$(document).ready(function () {
   $('div').find('p').css("background", "yellow");
   $('div').find('span').css("background", "pink");
});
Can this be done using chaining? The first line of code $('div').find('p'), will select all the <p> tag element in <div> and change background color. Since using find() we have filtered out all <p> elements so we need to use selector again to select <span>tag element and we can't use chaining. Fortunately, jQuery has .end() function which end the most recent filtering operation in the current chain and return to its previous state. Like,
$(document).ready(function () {
    $('div')
       .find('p').css("background", "yellow")
       .end()
       .find('span').css("background", "pink");
});
This chain searches for <p> tag element in <div> and turns their backgrounds yellow. Then .end() returns the object to its previous state which was before the call to find(), so the second find() looks for <span> inside <div>, not inside <p>, and turns the matching elements' backgrounds to pink. The .end() method is useful primarily when exploiting jQuery's chaining properties.
See Complete Code
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Thursday, May 30, 2013

Scroll Page Automatically by few pixels after every few seconds using jQuery

It would be nice feature for web pages if the web page scrolls automatically by few pixels after every 2, 3 or 5 seconds so that the users don't have to scroll it. This is quite useful for webpages having articles, posts, very long text or lengthy pages.

So, In this post you will find jQuery way to "Scroll Page Automatically by few pixels after every few seconds".

Related Post:

For the demo purpose, we will be scrolling the webpage by 200 pixels and after every 2 seconds. To do this, we need to use JavaScript "setInterval" method, which is responsible for calling a function/particular code after x seconds. So in this case, it would be 2 seconds.

Then, all you want is to get window scrollTop value and add 200 to it and then just scroll it.. Simple and Easy!!!!!
$(document).ready(function () {
    setInterval(function () {
        var iScroll = $(window).scrollTop();
        iScroll = iScroll + 200;
        $('html, body').animate({
            scrollTop: iScroll
        }, 1000);
    }, 2000);
});
Now, there is an issue which above approach. That is, once you reach at the bottom of the page you setInterval will keep on calling the function after every 2 seconds which is not desired. One way is to disable the automatic scrolling once user reaches at bottom of the page.

To do this, check if user has reached to bottom of the page and then call "clearInterval()" to stop setInterval.
$(document).ready(function () {
    var myInterval = false;
     myInterval = setInterval(function () {
        var iScroll = $(window).scrollTop();
        if (iScroll + $(window).height() == $(document).height()) {
            clearInterval(myInterval);
        } else {
            iScroll = iScroll + 200;
            $('html, body').animate({
                scrollTop: iScroll
            }, 1000);
        }
    }, 2000);
});
If the above solution don't work, then please make sure that you have include document type at top of the page.
<!DOCTYPE HTML>
The issue with above approach is that it gets executed only once. As once user reaches at bottom of the page, then setInterval is stopped. What if you want to have it again once user reaches at top of the page? Below jQuery code block exactly does the same thing.

As once bottom of the page is reached, then setInterval is stopped. So need to find a way to enable it again. And that can be done in $(window).scroll event. In this event, check if user has reached at top of the page. If yes, then reset setInterval.. That's it..

Note: For demo, I have set 500 as pixels to scroll.
$(document).ready(function () {
    var myInterval = false;
    myInterval = setInterval(AutoScroll, 2000);

    function AutoScroll() {
        var iScroll = $(window).scrollTop();
        iScroll = iScroll + 500;
        $('html, body').animate({
            scrollTop: iScroll
        }, 1000);
    }
    
    $(window).scroll(function () {
        var iScroll = $(window).scrollTop();
        if (iScroll == 0) {
            myInterval = setInterval(AutoScroll, 2000);
        }
        if (iScroll + $(window).height() == $(document).height()) {
            clearInterval(myInterval);
        }
    });
});
If the above solution don't work, then please make sure that you have include document type at top of the page.
<!DOCTYPE HTML>
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Thursday, April 18, 2013

Direct vs Delegated Events with jQuery on() method

jQuery added a new method called  on()  in release 1.7 which provides all functionality for attaching event handlers. And it has made other event handler event like live() and delegate() dead. This method was introduced due to performance issue with live() method.

Related Post:

There are 2 signaturs of  on()  method.
  1. .on(events[,selector] [,data ],handler(eventObject))
  2. .on(events[,selector] [,data])
In this post, we will focus on the one of the optional parameter named "selector". The official jQuery documentation about this parameter says,

" A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element."

As this is an optional parameter, so it can be omitted. The present/absence of this parameter defines Direct Event or Delegated Event. If it is absent, then it is called "Direct event", otherwise "Delegated event". First, we will see what Direct event means.

For example, there are 2 div element present on the page,
<div>First Div</div>
<div>Second Div</div>
And attach a click event on div element using on() method, which just alerts the clicked element text.
$(document).ready(function () {
    $('div').on('click', function() {
        alert("Clicked: " + $(this).html());
    });
});
So the above jQuery code instructs "HEY!!!! I want every div to listen to click event. And when you are clicked , give me alert." Now, this is absolutely fine and works like charm. This is called "Direct Event". But there is an issue with Direct events. Official jQuery document about Direct events says,

" Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()."

So for Direct events to work, the element has to present on the page. If it is added dynamically, it's not going to work.

Consider the same example, which now on click event adds a div element dynamically, after showing alert. But the click event don't get attached to dynamically added elements.
$(document).ready(function () {
    $('div').on('click', function() {
        alert("Clicked: " + $(this).html());
        $('<div>Dynamic Div</div>').appendTo('body');
    });
});
So when dynamically added div elements are clicked, nothing happens! As the event is not attached to them.
So, what is the solution now? Well, solution is to use "Delegated events". Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

When a selector is provided, the event handler is referred to as delegated. So let's modify the above jQuery code to have "Delegated event" instead of "Direct event".
$(document).ready(function () {
    $(document).on("click","div", function(){
        alert("Clicked: " + $(this).html());
        $('<div>Dynamic Div</div>').appendTo('body');
    });
});
So the jQuery code instructs "HEY!! document when your child element which is div gets clicked, give me alert and append a dynamic div to body." Using delegated event, you will find the same behavior for already present and dynamically added elements.
There is another advantage of using delegated event which is "much lower overhead". For example, On a table with 1,000 rows in its tbody, below code attaches a handler to 1,000 elements.
$("#Table tbody tr").on("click", function(event){
  alert($(this).text());
});
On the other side, using "Delegated event", attaching event handler to only one element which is tbody. The event only needs to bubble up one level (from the clicked tr to tbody).
$("#Table tbody").on("click", "tr", function(event){
  alert($(this).text());
});
Let's take another example, to explain "Delegated events". Consider following Html code.
<div id="container"> 
    <span> Span within Container div. </span>
    <br/> <span> Another span within Container div. </span>
</div>
And below is jQuery code to attach (delegated) click event on span element within div with ID "container" is,
$(document).ready(function () {
  var iCount = 1;
  $('div#container').on("click", "span", function () {
    alert("Clicked: " + $(this).html());
    var $dynSpan = $('<br/><span> Dynamic Span ' + iCount + '.</span>');
    $dynSpan.appendTo('div#container');
    iCount++;
  });
});
Here is another important tips "Attaching many delegated event handlers near the top of the document tree can degrade performance". For best performance, attach delegated events at a document location as close as possible to the target elements as done in above jQuery code. So instead of $(document).on("click","div#container span", function(){ , use $('div#container').on("click", "span", function () {

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Monday, April 8, 2013

Delay jQuery animation by few seconds

I got into a situation where I needed to start the animation after 2 seconds once the mouse is on the image. In other words, need to delay the animation for 2 seconds on mouseover event. So in this post I am sharing the jQuery solution to delay the animation by few seconds.

Related Post:

To delay execution of animation, use .delay() method which allows to delay the execution of functions that follow it in the queue. It accepts duration as parameter. Durations are given in milliseconds; higher values indicate slower animations, not faster ones.
$(document).ready(function () {
  $('img').mouseenter(function () {
     $(this).stop().delay(1000).animate({
         height: '+=50px',
         width: '+=50px'
     });
  });

  $('img').mouseleave(function () {
      $(this).stop().delay(1000).animate({
         height: '-=50px',
         width: '-=50px'
     });
  });
});
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Thursday, April 4, 2013

Difference between $('div') and $('<div/>') in jQuery

One of my colleague who is learning jQuery asked me what is the difference between $('div') and $('<div/>') , if used as selector. To explain more, take a look at below code.
$('<div/>').addClass('test');
$('div').addClass('test');
It is indeed quite confusing for someone who just started learning jQuery. So I went ahead and explained him about how they are different.

Related Post:

$('<div/>') : This creates a new div element. However this is not added to DOM tree unless you don't append it to any DOM element.

$('div') : This selects all the div element present on the page.

So, the code $('<div/>').addClass('test') will create a new div element and adds css class called "test". And $('div').addClass('test') will select all the div element present on the page and adds css class "test" to them.

As mentioned earlier that while using $('<div/>'), only new element gets created but it is still not added to DOM. One have to append it to any other element. For example, to append this newly created div to body, use below jQuery code.
$('<div/>').addClass('test').appendTo('body')

Hope you find this useful!!!!

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, April 2, 2013

jQuery: Difference between eq() and get()

In this post, find out what is the difference between jQuery  eq() and  get() method. Both the methods are used to find and select single element from set of elements and they both return single "element". And they both accept single int type parameter, which denotes index.

Related Post:

For example, take a look at below HTML. There is a <ul> element with 5 <li> elements.
<ul>
    <li>list item 1</li>
    <li>list item 2</li>
    <li>list item 3</li>
    <li>list item 4</li>
    <li>list item 5</li>
</ul>
And to select 3rd <li> element, use either get() or eq() and pass 2 as index. Keep in mind that index is zero-based.
$('li').get(2);
$('li').eq(2);
In the above code, both will return the 3rd <li> element. But then what is the difference between 2.

eq() returns the element as a jQuery object. This method constructs a new jQuery object from one element within that set and returns it. That means that you can use jQuery functions on it.

get() return a DOM element. The method retrieve the DOM elements matched by the jQuery object. But as it is a DOM element and it is not a jQuery-wrapped object. So jQuery functions can't be used.
$(document).ready(function () {
  $('li').eq(2).css('background-color', 'red'); //Works
  $('li').get(1).css('background-color', 'red'); // Error. Object #<HTMLLIElement> has no method 'css' 
});
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, March 12, 2013

OOPS!!!! jQuery Selectors NOT working...

OOPS!!!! jQuery Selectors NOT working.. A very common jQuery problem/issue that you must have face or may face. And there could be tons of reason of selectors not working properly like incorrect syntax, incorrect context.. But do you know there could be another reason which is element ID or css class name?

Yes, you read it right. Sometimes, if the ID or class containing meta characters such as @ # !" $ % &' ()*+,./:;<=>?[\]^`{|}~ like "foo.bar", "xyz@pqr" , "id#title"....

Related Post:

For example, if your element ID is "myid.3" then below code will not work.
$('#myid.3').text('DIV Content Updated');
From jquery API document :

"To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[\]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element with id="foo.bar", can use the selector $("#foo\\.bar")"


So, the correct syntax is,
$('#myid\\.3').text('DIV Content Updated'); 
So, if your ID contains any meta character then use backslashes for selecting elements. But it is not advisable to use meta-characters in DOM identifier as your HTML is not validated. Read http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...