Wednesday, 2 October 2013

JQUERY BASICS MANOHAR GOUD


<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Demo</title>
</head>
<body>
<a href="http://jquery.com/">jQuery</a>
<script src="jquery.js"></script>
<script>
// Your code goes here.
</script>
</body>
</html>


window.onload = function() {
alert( "welcome" );
}


$( document ).ready(function() {
// Your code here.
});



$( document ).ready(function() {
$( "a" ).click(function( event ) {
alert( "Thanks for visiting!" );
});
});

$( document ).ready(function() {
$( "a" ).click(function( event ) {
alert( "As you can see, the link no longer took you to jquery.com" );
event.preventDefault();
});
});


<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Demo</title>
</head>
<body>
<a href="http://jquery.com/">jQuery</a>
<script src="jquery.js"></script>
<script>
$( document ).ready(function() {
$( "a" ).click(function( event ) {
alert( "The link will no longer take you to jquery.com" );
event.preventDefault();
});
});
</script>
</body>
</html>



Adding and Removing an HTML Class

Important: You must place the remaining jQuery examples inside the ready event so that your code executes when the document is ready to be worked on.
Another common task is adding or removing a class.
First, add some style information into the <head> of the document, like this:
1
2
3
4
5
<style>
a.test {
font-weight: bold;
}
</style>
Next, add the .addClass() call to the script:
1
$( "a" ).addClass( "test" );
All <a> elements are now bold.
To remove an existing class, use .removeClass():
1
$( "a" ).removeClass( "test" );


<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$( document ).ready(function() {
console.log( "document loaded" );
});
$( window ).load(function() {
console.log( "window loaded" );
});
</script>
</head>
<body>
<iframe src="http://manohargoud.in"></iframe>
</body>
</html>







Tuesday, 1 October 2013

JQUERY INTRODUCTION MANOHAR GOUD


jQuery is a multi-browser (cf. cross-browser) JavaScript library designed to simplify the client-side scripting of HTML. It was released in January 2006 at BarCamp NYC by John Resig. It is currently developed by a team of developers led by Dave Methvin. Used by over 65% of the 10,000 most visited websites, jQuery is the most popular JavaScript library in use today.
jQuery is free, open source software, licensed under the MIT License. jQuery's syntax is designed to make it easier to navigate a document, select DOM elements, create animations, handle events, and develop Ajax applications. jQuery also provides capabilities for developers to create plug-ins on top of the JavaScript library. This enables developers to create abstractions for low-level interaction and animation, advanced effects and high-level, theme-able widgets. The modular approach to the jQuery library allows the creation of powerful dynamic web pages and web applications.
The set of jQuery core features — DOM element selections, traversal and manipulation —, enabled by its selector engine (named "Sizzle" from v1.3), created a new "programming style", fusing algorithms and DOM-data-structures; and influenced the architecture of other Javascript frameworks like YUI v3 and Dojo.
Microsoft and Nokia bundle jQuery on their platforms. Microsoft include it with Visual Studio for use within Microsoft's ASP.NET AJAX framework and ASP.NET MVC Framework while Nokia has integrated it into their Web Run-Time widget development platform. jQuery has also been used in MediaWiki since version 1.16.
jQuery includes the following features:
  • DOM element selections using the multi-browser open source selector engine Sizzle, a spin-off of the jQuery project
  • DOM traversal and modification (including support for CSS 1–3)
  • DOM manipulation based on CSS selectors that uses node elements name and node elements attributes (id and class) as criteria to build selectors
  • Events
  • Effects and animations
  • AJAX
  • Extensibility through plug-ins
  • Utilities - such as user agent information, feature detection
  • Compatibility methods that are natively available in modern browsers but need fall backs for older ones - For example theinArray() and each() functions.
  • Multi-browser (not to be confused with cross-browser) support.







JQUERY BEGINNING MANOHAR GOUD



 Before the beginning of jQuery


Before the beginning of jQuery and lots of other stuff, there was the HTTP Protocol. Guess what, the HTTP protocol barely evolved since its beginning. If you don't understand the HTTP protocol you're pretty doomed if you want to do high quality web development. But the bright side is, it never changes...

Forget about the formal definitions of the HTTP protocol in Wikipedia, here's what you got to know: The HTTP protocol is composed of client and servers where clients are making requests to servers to get content from it:

clients are requesting files from web servers according to a network protocol

As you can see clients are only requesting files to the server and the servers are only serving content to clients.

There's nothing complicated here and there's no particular technology involved either. In fact, whether the client is a web browser or a telnet session, the server couldn't care less. On the other side, if the server is running Apache, the client doesn't care either. AS LONG AS BOTH ARE FOLLOWING THE HTTP PROTOCOL.

It's the separation between the two (what's going through the wires in the middle of the previous picture) that makes the whole thing transparent and working since 1990 even thought the technologies used on clients and servers evolved (Browsers versions, Coldfusion, ASP, PHP, Perl, etc).


How browsers internally represents the HTML content


We can now toss the server portion out of the way since it only serves content. Let's focus our attention to a specific type of client, the browser.

As we saw earlier, the browser only request some content from the server and process it:

the html in text format received from the server is read by the browser

As human we usually represents concepts with something readable by us like text and symbols and HTML is only another example: we represent web pages with a markup language (HTML). But for machines, parsing text can be a tedious task. To be more efficient, browsers are parsing HTML pages only once after receiving the response from the server. They then transform the text representation of the web page into a data structure in the form of a tree called the DOM (document object model). That way they can also validate the document and have a more flexible rendering engine.

from the html received, the browser constructs the document object model

A very very important thing to know is that if the source document contains logical errors (The HTML document is not standard compliant), nobody knows how the DOM will be constructed. Internet Explorer will react differently than Chrome when encountering errors because the standard doesn't define error handling guidelines. Afterwards, you could have surprises using JavaScript or jQuery to manipulate the DOM as it may be different from one browser to another.

As a side note, when you do a "view page source" in your favorite browser, it only shows you the original text it downloaded from the server earlier and not what's in memory! That's why if you've manipulated the DOM with JavaScript and then do a "view source" you won't see the changes. But more on that later.


Dynamically changing the page's content (DOM)


It's possible to manipulate the DOM with a client side language called JavaScript. JavaScript can manipulate the properties and the elements of the DOM as soon as the page is loading and afterwards on events triggered by the user. The source of the image could be changed for example:

javascript is a programming language and is a collection of functions and objects to manipulate the dom

Sounds good isn't it? No. The problem is that JavaScript functions and capabilities are implemented differently across browsers vendors. For example, a function to do something could be named differently in two different browsers. How can that be? This is another story.. but for now, your scripts must take this into account and it can be a real pain.


A Special case with AJAX


Before hitting jQuery, I feel that now is the proper time to talk about AJAX. AJAX is nothing more than a standard HTTP request made to the server (see above, first image). AJAX doesn't bend the rules. It obeys to the same laws of the HTTP protocol. But normally, when the browser navigates to another page (or image, or text file), the current one is wiped out from memory and visually cleared to give its place to the new one we're navigating to. In AJAX, nothing is cleared out from memory and the current page stays there. That's the only difference. So, with AJAX, you can fetch new content from the server without losing the current DOM. The content retrieved is passed to the document as a JavaScript variable. You can then insert this new content into the DOM or do whatever it please you. So you see, there is almost no difference excepted: this is not the browser window that is handling the new content, this is you in JavaScript. That being said, let's finally look at jQuery.


Where jQuery is sitting in the big picture


To ease JavaScript development, several JavaScript libraries were created to encapsulate the native JavaScript functions and have a more uniform programming environment. That's also the case for jQuery. So we have all the knowledge now to know that jQuery is layer of abstraction above the native JavaScript functions of the browser:

jquery is a javascript library that eases the manipulation of the dom as opposed to the use of javascript alone

When I see this, two things comes to mind:


  1. jQuery can't do more things than JavaScript can actually do... right? Right. I know, it's a shocker.
    -and-
  2. Where the hell "jquery sqlserver out of memory" can be coming from?

The same thing applies to "mvc and google map = jquery". You can now understand that basic key concepts have been mixed up or never truly understood by those googlers. But fortunately, now you know why! (or already knew and thinking the pace of this article is horribly slow)


jQuery And Other Libraries


So jQuery provide a more uniform and easier way to manipulate the DOM. But nothing prevent you to access DOM elements yourself using natives JavaScript functions at the same time. Another amusing kind of keywords I encounter on my site is keywords like "jquery and google maps". People want to use jQuery everywhere, even with perfectly independent JavaScript libraries like Google Maps. That makes no sense. Again, I think it's just a misunderstanding. Independent libraries are not encapsulated by other independent libraries... they sit next to each other:

jquery can be used along with other libraries but rarely encapsulates them

Sure sometimes a function in jQuery could be helpful in another context, but that's different than trying to do everything in jQuery. It makes little sense to try to encapsulate a library that already encapsulates your native JavaScript functions.


jQuery Architecture


jQuery seems complicated at first but lets write ourselves a little library first and then look at the real deal. Our library will have two functions, a regular function to get a DOM element, and another static function to add two numbers:


function myLibrary(id) {
    return document.getElementById(id);
}

myLibrary.Add = function(a, b) {
    return a + b;};
var myDiv = myLibrary('div1');
var sum = myLibrary.Add(1, 3);

We're pretty happy about our library but the function name is pretty long. What if we create an alias of the main function to make it shorter. Let's take the dollar sign ('$') which is nothing more in JavaScript than a 27th letter in the alphabet. The dollar sign is also more distinctive and less prone to name clashes:


var $ = myLibrary;      // let's make an alias of our library
var myDiv = $('div1');  // do the same as usual
var sum = $.Add(1, 3);

That's great! And guess what, with my previous examples you saw how jQuery was constructed (roughly). This is basically the same thing. If you were shy about the strange nature of the library, you should now be more comfortable with it.

To prove that jQuery is like our little library, here's something you can try. The jQuery's library defines a "jQuery" function and the dollar sign is an alias to it:


alert(jQuery);       // shows a function
alert(== jQuery);  // shows true

There's two main parts in the jQuery's library (like ours), a selector function "$()" and static functions (called utility functions) "$.Xyz". You can see an examples of both in the next snippet (actual jQuery code):


var myDiv = $('#div1');
var trimmed = $.trim('  hello world ');

Selecting and Manipulating Elements with jQuery Selectors


Maybe you noticed a little difference between our library and jQuery. The parameter to the function that selects DOM elements are different:

var myLibDiv = myLibrary('div1');
var jQueryDiv = jQuery('#div1');

This is because jQuery is very flexible with the way you can select DOM elements with the jQuery selector function. You can query the DOM with other properties than object ids. Inspired by the CSS syntax, jQuery actually offer many ways to match objects in a document:


jQuery('#id');        // Match objects by id
jQuery('.class');     // Match objects by CSS class
jQuery('#id1, #id2'); // Match objects having id1 or id2
[...]

See Selectors in the jQuery documentation to learn many other ways to match and retrieve DOM elements from a document.

There's another difference between our library and jQuery. Our library can only find one element at a time (by its id) while jQuery can match multiple elements in a single selector function call:

// returns a single element having the id 'mainTitle'
var title = myLibrary('mainTitle');
// returns every element having the class 'title'
var titles = jQuery('.title');

As opposed to our little library, what is returned by the jQuery selector function is not the real DOM objects. They are encapsulated by another jQuery object. So if we take this example again:


var myvar = jQuery('.title');

Visually, it would appear like this:

the dom objects found when using the selector are put in a jquery object

So what are the benefits? Remember that every JavaScript implementations across browsers are a little different. If the jQuery selector were to return DOM objects, it would have little value as you would have to manipulate those objects just like before. After all, what's the purpose of selecting objects without manipulating them. And jQuery provide a standard way across browsers to do just that and this is where the real power of jQuery sits:

the object returned by the jquery selector exposes various functions that are acting on the dom objects

That's it, the jQuery object returned provide manipulation functions that acts on every DOM objects found! Here's an example that would hide every object with the class 'title':


var myvar = $('.title');
myvar.hide();
// Hint, the last two lines could be simplified as
$('.title').hide();

To know every function that you can apply on matched objects, please refer to the jQuery API documentation online.

One last thing before closing on this section. Each and every function like the 'hide' function we used previously are also returning a jQuery object containing the DOM elements just like the main jQuery selector function.This is really powerful:

// return a jQuery object containing DOM elements
var myvar = $('.title');
// returns also a jQuery object containing our DOM elements
var myvar2 = myvar.hide();
// same here
var myvar3 = myvar2.height(200);
// same here
var myvar4 = myvar3.show();
// Hint, the last lines could be simplified as
$('.title').hide().height(200).show();

The above snippet, even though pretty pointless, hides every titles to set their height to 200px before showing them again. The succession of function calls is called (no pun intended) chaining.

I guess you now have what it takes to fully understand jQuery selectors and manipulators. Let's move on to utilities functions.


jQuery utility functions


If you remember, our little library had a static 'Add' function:

myLibrary.Add = function(a, b) {
    return a + b;};
var sum = myLibrary.Add(1, 3);

Just like that, jQuery provides a lot of useful functions to further encapsulate the native JavaScript functions of the browsers. Here's an example (we already saw the 'trim' function):

$.get('/index.html', function(data) {
    alert(data);
});

The 'get' function is making an ajax request to retrieve asynchronously some content from the server.