Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Tuesday, 16 July 2013

JQuery Simple example


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-1.8.0.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
   // alert($("input[name=first_name].val()"));
   // $("p").hide();
   //alert( $("input[#first_name]").val() );
   alert( $("#first_name").val() );
  });
});
</script>
</head>

<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p id='test'>This is another paragraph.</p>
<button>Click me</button>
<input type="text" id="first_name" value="" />
</body>
</html>



================
Not too long ago I wrote an article for Six Revisions called Getting Started with jQuery that covered some important things (concept-wise) that beginning jQuery developers should know. This article is the complete opposite; there’s no concepts, no principles, and very little lecturing — just some straight example code with brief descriptions demonstrating what you can do with jQuery.
This fast-paced tutorial should be able to get beginners up and running with jQuery very quickly, while also providing a good overview of what jQuery is capable of (although jQuery’s capabilities go far beyond this beginning tutorial).
Keep in mind that this tutorial is just a bunch of straightforward, superficial code examples and very brief explanations for beginners who want to avoid all the jargon and complexities. But I still highly recommend that all beginners get past this stuff by means of a good book, some more in-depth tutorials online, or by using the jQuery documentation.

Link to jQuery’s Source Code Remotely

This is an optional technique that many developers are using today. Instead of hosting the jQuery source code on your own server, you can link to it remotely. This ensures the fastest possible download time of the source code, since many users visiting your site might have the file already cached in their browser. Here is how your <script> tag should look:
  1. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js?ver=1.4.0"></script>  

Running Code Unobtrusively When the DOM is Ready

The first thing you need to be up and running with jQuery is what’s called the “document ready” handler. Pretty much everything you code in jQuery will be contained inside one of these. This accomplishes two things: First, it ensures that the code does not run until the DOM is ready. This confirms that any elements being accessed are actually in existence, so the script won’t return any errors. Second, this ensures that your code is unobtrusive. That is, it’s separated from content (HTML) and presentation (CSS).
Here is what it looks like:
  1. $(document).ready(function() {  
  2.     // all jQuery code goes here  
  3. });  
Although you will normally include your jQuery code inside the above handler, for brevity the rest of the code examples in this tutorial will not include the “ready” handler.

Selecting Elements in jQuery

The jQuery library allows you to select elements in your HTML by wrapping them in $("") (you could also use single quotes), which is the jQuery wrapper. Here are some examples of “wrapped sets” in jQuery:
  1. $("div"); // selects all HTML div elements  
  2. $("#myElement"); // selects one HTML element with ID "myElement"  
  3. $(".myClass"); // selects HTML elements with class "myClass"  
  4. $("p#myElement"); // selects paragraph elements with ID "myElement"  
  5. $("ul li a.navigation"); // selects anchors with class "navigation" that are nested in list items  
jQuery supports the use of all CSS selectors, even those in CSS3. Here are some examples of alternate selectors:
  1. $("p > a"); // selects anchors that are direct children of paragraphs  
  2. $("input[type=text]"); // selects inputs that have specified type  
  3. $("a:first"); // selects the first anchor on the page  
  4. $("p:odd"); // selects all odd numbered paragraphs  
  5. $("li:first-child"); // every list item that's first child in a list  
jQuery also allows the use of its own custom selectors. Here are some examples:
  1. $(":animated"); // selects elements currently being animated  
  2. $(":button"); // selects any button elements (inputs or buttons)  
  3. $(":radio"); // selects radio buttons  
  4. $(":checkbox"); // selects checkboxes  
  5. $(":checked"); // selects selected checkboxes or radio buttons  
  6. $(":header"); // selects header elements (h1, h2, h3, etc.)  

Manipulating and Accessing CSS Class Names

jQuery allows you to easily add, remove, and toggle CSS classes, which comes in handy for a variety of practical uses. Here are the different syntaxes for accomplishing this:
  1. $("div").addClass("content"); // adds class "content" to all <div> elements  
  2. $("div").removeClass("content"); // removes class "content" from all <div> elements  
  3. $("div").toggleClass("content"); // toggles the class "content" on all <div> elements (adds it if it doesn't exist, and removes it if it does)  
You can also check to see if a selected element has a particular CSS class, and then run some code if it does. You would check this using an if statement. Here is an example:
  1. if ($("#myElement").hasClass("content")) {  
  2.     // do something here  
  3. }  
You could also check a set of elements (instead of just one), and the result would return “true” if any one of the elements contained the class.

Manipulating CSS Styles with jQuery

CSS styles can be added to elements easily using jQuery, and it’s done in a cross-browser fashion. Here are some examples to demonstrate this:
  1. $("p").css("width""400px"); // adds a width to all paragraphs  
  2. $("#myElement").css("color""blue"// makes text color blue on element #myElement  
  3. $("ul").css("border""solid 1px #ccc"// adds a border to all lists  

Adding, Removing, and Appending Elements and Content

There are a number of ways to manipulate groups of elements with jQuery, including manipulating the content of those elements (whether text, inline elements, etc).
Get the HTML of any element (similar to innerHTML in JavaScript):
  1. var myElementHTML = $("#myElement").html(); // variable contains all HTML (including text) inside #myElement  
If you don’t want to access the HTML, but only want the text of an element:
  1. var myElementHTML = $("#myElement").text(); // variable contains all text (excluding HTML) inside #myElement  
Using similar syntax to the above two examples, you can change the HTML or text content of a specified element:
  1. $("#myElement").html("<p>This is the new content.</p>"); // content inside #myElement will be replaced with that specified  
  2. $("#myElement").text("This is the new content."); // text content will be replaced with that specified  
To append content to an element:
  1. $("#myElement").append("<p>This is the new content.</p>"); // keeps content intact, and adds the new content to the end  
  2. $("p").append("<p>This is the new content.</p>"); // add the same content to all paragraphs  
jQuery also offers use of the commands appendTo()prepend(),prependTo()before()insertBefore()after()insertAfter(), which work similarly to append but with their own unique characteristics that go beyond the scope of this simple tutorial.

Dealing with Events in jQuery

Specific event handlers can be established using the following code:
  1. $("a").click(function() {  
  2.     // do something here  
  3.     // when any anchor is clicked  
  4. });  
The code inside function() will only run when an anchor is clicked. Some other common events you might use in jQuery include:
blurfocushoverkeydownloadmousemoveresizescroll,submitselect.

Showing and Hiding Elements with jQuery

The syntax for showing, hiding an element (or toggling show/hide) is:
  1. $("#myElement").hide("slow"function() {  
  2.     // do something once the element is hidden  
  3. }  
  4.   
  5. $("#myElement").show("fast"function() {  
  6.     // do something once the element is shown  
  7. }  
  8.   
  9. $("#myElement").toggle(1000, function() {  
  10.     // do something once the element is shown/hidden  
  11. }  
Remember that the “toggle” command will change whatever state the element currently has, and the parameters are both optional. The first parameter indicates the speed of the showing/hiding. If no speed is set, it will occur instantly, with no animation. A number for “speed” represents the speed in milliseconds. The second parameter is an optional function that will run when the command is finished executing.
You can also specifically choose to fade an element in or out, which is always done by animation:
  1. $("#myElement").fadeOut("slow"function() {  
  2.     // do something when fade out finished  
  3. }  
  4.   
  5. $("#myElement").fadeIn("fast"function() {  
  6.     // do something when fade in finished  
  7. }  
To fade an element only partially, either in or out:
  1. $("#myElement").fadeTo(2000, 0.4, function() {  
  2.     // do something when fade is finished  
  3. }  
The second parameter (0.4) represents “opacity”, and is similar to the way opacity is set in CSS. Whatever the opacity is to start with, it will animate (fadeTo) until it reaches the setting specified, at the speed set (2000 milliseconds). The optional function (called a “callback function”) will run when the opacity change is complete. This is the way virtually all callback functions in jQuery work.

jQuery Animations and Effects

You can slide elements, animate elements, and even stop animations in mid-sequence. To slide elements up or down:
  1. $("#myElement").slideDown("fast"function() {  
  2.     // do something when slide down is finished  
  3. }  
  4.   
  5. $("#myElement").slideUp("slow"function() {  
  6.     // do something when slide up is finished  
  7. }  
  8.   
  9. $("#myElement").slideToggle(1000, function() {  
  10.     // do something when slide up/down is finished  
  11. }  
To animate an element, you do so by telling jQuery the CSS styles that the item should change to. jQuery will set the new styles, but instead of setting them instantly (as CSS or raw JavaScript would do), it does so gradually, animating the effect at the chosen speed:
  1. $("#myElement").animate(  
  2.     {  
  3.         opacity: .3,  
  4.         width: "500px",  
  5.         height: "700px"  
  6.     }, 2000, function() {  
  7.         // optional callback after animation completes    
  8.     }  
  9. );  
Animation with jQuery is very powerful, and it does have its quirks (for example, to animate colors, you need a special plugin). It’s worth taking the time to learn to use the animate command in depth, but it is quite easy to use even for beginners.

This is Just the Beginning

There is so much more you can do with jQuery beyond these basics I’ve introduced here. I highly recommend that all developers buy a good book on jQuery, and also take the time to learn some important JavaScript concepts (like anonymous functions, closures, scope, etc.) in order to be able to use jQuery in a more powerful way.
And please note that I’ve introduced a lot of commands and syntaxes in a very superficial manner, without explaining many of the problems you could have with some of these, so if you do run into problems, you can check out the jQuery documentation.

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...