Showing posts with label Jquery. Show all posts
Showing posts with label Jquery. Show all posts

jQuery Tutorial for Beginners - Hello World Example

Below is a Jquery example of how to print "Hello World" to the Console.

<html>
<head>
<title>jQuery Example in Developersarena</title>
<script type="text/javascript" 
   src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type="text/javascript">
   $(document).ready(function(){
      document.write("Hello, World!");
   });
</script>   
</head>
<body>
<h1>Hello</h1>
</body>
</html>

Top 10 frequently asked JQUERY interview questions

Below are the top 10 Jquery questions that are frequently asked in Interviews

1.  What is JQUERY ?

jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.

2 . What is difference between jQuery's ready and holdReady ?
jQuery's ready is an event which gets triggered automatically when DOM is ready while holdReady is a signal/flag to hold this triggering. holdReady was included in 1.6 version and it works only if used before the execution/triggering of ready event. Once ready event is fired, it has nothing to do. It is useful in dynamically loading scripts before the ready starts. It release ready event execution when used with a true parameter

3. How do you update ajax response with id " username"

function updateStatus() {
     $.ajax({
            url: 'updateUsrName.htm',
            success: function(response) {
             // update username
             $('#username').html(response);
         }
     });
}


4. How do you get the text value of a selected option in JQUERY ?

$("#proglang").val();
<select id="proglang">
   <option value="1">Java</option>
   <option value="2">Javascript</option>
   <option value="3">Jquery</option>
   <option value="4">Visual Basic</option>
   <option value="5">Unix</option>
</select>

$("#proglang option:selected").text();

5.Name any four paremeter of Jquery ajax method

data : Specifies data to be sent to the server
url : Specifies the URL to send the request to. Default is the current page
type : Specifies the type of request. (GET or POST)
cache: A Boolean value indicating whether the browser should cache the requested pages. Default is true beforeSend(xhr): A function to run before the request is sent

5.What is $() in jQuery library?

 $() function is used to wrap any object into jQuery object, which then allows you to call various method defined jQuery object. You can even pass a selector string to $() function, and it will return jQuery object containing an array of all matched DOM elements.

6 . Difference between JavaScript window.onload event and jQuery ready function?

Main difference between JavaScript onload event and jQuery ready function is that former not only waits for DOM to be created but also waits until all external resources are fully loaded including heavy images, audios and videos.  If loading images and media content takes lot of time that user can experience significant delay on execution of code defined in window.onload event. On the other hand jQuery ready() function only wait for DOM tree, and does not wait for images or external resource loading, means faster execution. Another advantage of using jQuery $(document).ready() is that you can use it multiple times in your page, and browser will execute them in the order they appear in HTML page, as opposed to onload technique, which can only be used for a single function. Given this benefits, it's always better to use jQuery ready() function than JavaScript window.onload event.

7. How can you call a method inside code-behind using jQuery ?
We can call a method inside code-behind By $.ajax and by declaring method a WebMethod

8.What are the advantages of JQUERY ?

The main advantages to adding jQuery are :
  • browser compatibility - doing something like .attr() is much easier than the native alternatives, and won't break across browsers.
  • simplification of usually complicated operations - if you'd like to see a well written cross browser compatible version of an XHR method, take a look at the source for $.ajax - for this method alone it's almost worth the overhead of jQ.
  • DOM selection - simple things like binding events & selecting DOM elements can be complicated and differ per-browser. Without a lot of knowledge, they can also be easily written poorly and slow down your page.
  • Access to future features - things like .indexOf and .bind are native javascript, but not yet supported by many browsers. However, using the jQuery versions of these methods will allow you to support them cross browser.
9. What is the difference between onload() and document.ready() function used in jQuery

  • We can have more than one document.ready() function in a page where we can have only one body unload function.
  • document.ready() function is called as soon as DOM is loaded where body.onload() function is called when everything gets loaded on the page that includes DOM, images and all associated resources of the page.
  • Document.ready() function is called as soon as DOM is loaded.
  • onload() function is called when everything (DOM, images)gets loaded on the page.
10. What is difference between jQuery.get() and jQuery.ajax() method?

ajax() method is more powerful and configurable, allows you to specify how long to wait and how to handle error, get() is a specialization to over ajax just to retrieve some data.

How to use Jquery Autocomplete


The following example shows the usage of autocomplete functionality in Jquery. copy this code into your html editor and save it.

Then run the html page. Once you type the letter "a" you will be seeing the options which can be selected for autocomplete.

<!doctype html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <title>jQuery Autocomplete functionality</title>
      <link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
      <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
      <script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
      <!-- Javascript -->
      <script>
         $(function() {
            var availableLanguages = [
               "Java",
               "Visual Basic",
               "Oracle",
               "C++",
            ];
            $( "#automplete1" ).autocomplete({
               source: availableLanguages
            });
         });
      </script>
   </head>
   <body>
      <!-- HTML -->
      <div class="ui-widget">
         <p>Type input</p>
         <label for="automplete1">Programming Languages: </label>
         <input id="automplete1">
      </div>
   </body>
</html>

Improve your jQuery - 25 excellent tips

jQuery is awesome. I've been using it for about a year now and although I was impressed to begin with I'm liking it more and more the longer I use it and the more I find out about it's inner workings.

I'm no jQuery expert. I don't claim to be, so if there are mistakes in this article then feel free to correct me or make suggestions for improvements.

I'd call myself an "intermediate" jQuery user and I thought some others out there could benefit from all the little tips, tricks and techniques I've learned over the past year. The article also ended up being a lot longer than I thought it was going to be so I'll start with a table of contents so you can skip to the bits you're interested in.
Table of Contents

    *   1.  Load the framework from Google Code
    *   2.  Use a cheat sheet
    *   3.  Combine all your scripts and minify them
    *   4.  Use Firebug's excellent console logging facilities
    *   5.  Keep selection operations to a minimum by caching
    *   6.  Keep DOM manipulation to a minimum
    *   7.  Wrap everything in a single element when doing any kind of DOM insertion
    *   8.  Use IDs instead of classes wherever possible
    *   9.  Give your selectors a context
    * 10.  Use chaining properly
    * 11.  Learn to use animate properly
    * 12.  Learn about event delegation
    * 13.  Use classes to store state
    * 14.  Even better, use jQuery's internal data() method to store state
    * 15.  Write your own selectors
    * 16.  Streamline your HTML and modify it once the page has loaded
    * 17.  Lazy load content for speed and SEO benefits
    * 18.  Use jQuery's utility functions
    * 19.  Use noconflict to rename the jquery object when using other frameworks
    * 20.  How to tell when images have loaded
    * 21.  Always use the latest version
    * 22.  How to check if an element exists
    * 23.  Add a JS class to your HTML attribute
    * 24.  Return 'false' to prevent default behaviour
    * 25.  Shorthand for the ready event

7 reasons why you really should learn jQuery

Below are my 7 reasons why you should learn a javascript framework, and that the best one to learn about is jQuery.
1. jQuery seperates behavior from markup
In HTML markup it is still quite common to see things like this:

Even though the validate() function can be placed in an external file, in effect we are still mixing markup with logic and events here. jQuery allows you to completely seperate the two. With jQuery, the markup would look like this:

Next, the seperate JS file will contain the following event subscription code:
$("myform").submit(function() {
...your code here
)}

This allows for very clean markup with a lot of flexibility. jQuery takes javascript out of your markup, much like CSS took the style out of markup years ago.
2. Write less, do more
Write less, do more - it is the jQuery slogan, and it is an accurate one. Using jQuery's advanced selectors, you can do amazing things in just a few lines of code. You do not need to worry about browser differences (much), there is full Ajax-support and many other abstractions that make you more productive. jQuery takes javascript to a higher level. Here's a very simple example:
$("p.neat").addClass("ohmy").show("slow");
That little snippet loops through all
elements with the class "neat" and then adds the class "ohmy" to it, whilst slowly showing the paragraph in an animated effect. No browser checks, no loop code, no complex animation functions, just one line of code!
3. Performance
Out of the big Javascript frameworks, jQuery understands performance best. The minimized and gzipped version is only 18K in size, despite tons of new features in various releases, this number has hardly changed. With each release, major performance improvements have been made. This article is telling of the raw speed of jQuery and the focus that their developers have on it. Combine this with the new generation of browsers (Firefox 3, Google Chrome) that have fast javascript engines on board, and you have a whole new wealth of possibilities in creating rich web applications.
4. It is a "standard"
JQuery is not an official standard, let that be clear. However, the industry support for jQuery is overwhelming. Google uses it, and even hosts it for you. Dell, Digg, Wordpress, Mozilla and many others use it too. Microsoft is even shipping jQuery with Visual Studio. With so much weight behind this framework, you can consider it a safe choice for the future, and a safe bet to invest time in.  
5. Plugins!
There are thousands of plugins developed on top of jQuery. You can use it for form validation, galleries, field hints, animation, progress bars, you name it, it is available. The jQuery community is an eco-system, not just a library. This further supports reason #4, it is a safe choice. By the way, did you know that jQuery actively works together with their "competitors", such as Prototype. It looks like they're here to improve the overall state of javascript, not just for their own benefit.
6. It costs you little time
Of course it will cost you time to truly learn jQuery, especially if you will be writing lots of code or even your own plugins. However, you can do this in bits and pieces, there are tons of examples out there and it is really easy to get started. My advise is to first have a look in the plugin pool before you code something yourself. Next, have a look at the actual plugin code to see how it works. In short, learning jQuery is no huge investment, you can be productive right away and increase your skill in small increments.
7. Fun
I found working with JQuery to be a lot of fun. It is fresh, short and you quickly get results. It solves many nagging javascript problems and annoyances. I used to hate javascript coding but (somewhat) enjoy it now. With the basics fixed, one can now really think about developing next-generation web applications, without being slowed down by an inferior language or tool. I believe in the "Write less, do more" slogan.It is true.

Courtesy :ferdychristan

The jQuery animate() step callback function

     You can now extend jQuery animations with a function that is fired on every step of the animation that changes the style of the element being animated. It can be extended for specific css properties, or even to create a custom animation type.For example, you can pass in an extra step function to .animate() to perform actions like animation synchronization.
$("#go").click(function(){
    $(".block:first").animate({ left: 100 }, {
      duration: 1000,
      step: function(now, fx){
        $(".block:gt(0)").css("left", now);
      }
    });
});
Fortunately, a quick search on Google for “jquery animate step” will 
yield the 
jQuery 1.2 release notes that sheds a bit of light on
 the step function: 

How to Develop a JQuery plugin easily

jQuery is the most popular JavaScript library and many sites adopt it for dynamic effects and Ajax functionality. However, relatively few developers delve into the depths of plugin development.
Why a plugin?
First of all, you might ask yourself why you'd want to develop a plugin. The first and best reason is the ability to maintain chainability. When people ask me the best feature of jQuery, I'd probably mention the chainability. It allows you do do things like:
Code:
$('.className').addClass('enabled').append('Click here').click( func );
This would take every element with a class name of 'className', add a new class name to it, append some HTML, and set a click event handler. When you develop a plugin, you have the ability to intject your own functionality while still maintaining the chain.Another reason to develop a jQuery plugin is simply to be consistent with the jQuery ethos. The jQuery ethos, in my opinion, is that the HTML element is king (or queen — lest I be mysoginistic about my HTML elements). It's all about getting elements and then performing actions on those elements.Now, let's take a look at how to create a plugin, of which there are two possible approaches.
Approach 1: The Function
jQuery.log = function(message) { if(window.console) { console.debug(message); } else { alert(message); } };
In this example, a log function has been attached to the jQuery object. You can then call this in your code using jQuery.log('my message') or $.log('my message'). There's no chainability or HTML elements involved (unless you add that into your code).

Approach 2:

jQuery.fn.newMethod = function(){ return this; }
The this keyword refers to the current jQuery object. You'll have access to jQuery's methods and functions. If you need to perform an action on each element then you can do something like this:
jQuery.fn.newMethod = function(){
    return this.each(function(){
        alert(this);
    });
}
The this keyword within the inner function refers to the current HTML element, which won't have access to the jQuery methods (although, it's as easy as wrapping it in the jQuery object to get those methods back).

Don't use $

When developing a plugin, you'll want to avoid using the familiar dollar function, $, to avoid any conflicts. jQuery has a no-conflict mode for turning the alias on and off. If you want, you can alias the jQuery function within your plugin. It'll be self-contained and avoid any outside conflicts.

jQuery Twitter Plugins – Add Tweets To Your Website

The plugin is so easy to use, customizable & unobstrusive.
Integrating social profiles with websites is a very popular trend as they represent a content.
For Twitter, if you have an account and want to add tweets to your website, these  jQuery Tweeter plugins will help you for sure:

Step 1:After inserting the jquery-twitter.js file to your website, simply create a divnamed "twitter" at where the feeds will be displayed.
Step 2:This jQuery code does the rest:
$(document).ready(function() {
    $("#twitter").getTwitter({
        userName: "jquery",
        numTweets: 5,
        loaderText: "Loading tweets...",
        slideIn: true,
        showHeading: true,
        headingText: "Latest Tweets",
        showProfileLink: true
    });
});