

































Thông minh ~> 1% Chăm chỉ ~> 4% May mắn ~> 5% Liều ~> 90%
<div id="object" class="message"> lorem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit </div>
.message{ border:1px solid #CCCCCC; padding: 5px; width: 150px; background-color:#F4F4F8; text-align:justify; position:absolute; top:50px; }
//hide the object with blink effect $("#blink_out").click(function() { $("#object").fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100).fadeOut(100); });
//show the object with blink effect $("#blink_in").click(function() { $("#object").fadeIn(100).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100); });
//bounce an object $("#bounce").click(function() { $("#object").fadeIn(100).animate({top:"-=20px"},100).animate({top:"+=20px"},100).animate({top:"-=20px"},100) .animate({top:"+=20px"},100).animate({top:"-=20px"},100).animate({top:"+=20px"},100); });In the above code, we’ve used jquery’s animate() function to bounce an “image” or “div”. The “top” attribute of the object is toggled to show the bouncing effect on the object.
Python-jQuery Example Python-jQuery Example
Hello, world!Show box
Hello, world!Show box
Show element dimensions
$("a").unbind();This will remove any event handlers that you have attached with the bind() function. However, you may want to only remove event subscriptions of a specific type, for instance clicks and doubleclicks: $("a").unbind("click doubleclick"); Simply separate the event types with a comma. Here is a more complete example, where you can see it all in effect:
Test 1 Test 2
Test
It requests a PHP script which is doing a very complicated calculation (as you will see from the result), which means that it usually takes ~3 seconds to finish. Now, try the example and push the button several times after each other. The same "calculation" will be performed multiple times and the result will also be displayed multiple times (with a 3 second delay). Fortunately, a call to the get() method and pretty much any other jQuery AJAX method, returns an object which, among others, contains an abort() method. We can save this reference and then call the abort() method on it if needed. Have a look at this slightly modified example:
We start off by defining a common variable for containing the request reference. In the PerformAbortableCalculation() method, we assign the return value of the get() call to this variable, but before we do so, we check to see if it's null (the method hasn't been used yet) and if not, we call the abort() method on it. If you try this example and click several times, you will see that no matter how many times you click the button, it only executes the callback function once.
Right before performing the AJAX request, we change the text of the sender (the button which calls the function). As soon as it succeeds, we set it back. That's the simplest form of progress. Another approach is to show a piece of text somewhere on the page, but the most common way of doing it is to show a little piece of graphic which illustrates that the browser is currently working. You could make one yourself, or even better: Use one of the great online generators, for instance http://ajaxload.info/. I've created one, as you can see in the next example:
The process is pretty much the same, but instead of setting a text, we show and hide an existing image. You can place the image in a spot that the user is most likely to notice or dynamically place the image next to button/link clicked, if you have more than one. The possibilities are really endless. There is one problem with the above examples though: If the request fails for some reason, the progress is shown but never removed again. We can fix this by subscribing to the error event, where we can then remove the progress and then show an error message. Check out this example:![]()
It's pretty much identical to the first example, but here we call the error function on the returned AJAX object and pass in a callback function which should be called if the request fails, which it will in this example, since I have changed the path for the requested file to something which doesn't exist.
$("div > a")This selector will find all links which are the direct child of a div element. Replacing the greater-than symbol with a simple space will change this to match all links within a div element, no matter if they are directly related or not:
$("div a")Here's an example where we color bold tags blue if they are directly descending from the first test area:
As you will see, only the first bold tag is colored. Now, if you had used the second approach, both bold tags would have been colored blue. Try the following example, where the only thing changed is the greater-than character which has been replaced with a space, to note that we also accept non-direct descendants or "grand children" as they are sometimes called:Bold text Italic textBold text 2 Italic text 2Bold text 3
Now the cool thing is that you can actually go back up the hierarchy if needed, using the parent() method. We'll look into that in another chapter of this tutorial.Bold text Italic textBold text 2 Italic text 2Bold text 3
Test 1We use the attribute selector to find all elements on the page which has a title attribute and then underline it. As mentioned, this will match elements with a title element no matter what their value is, but sometimes you will want to find elements with a specific attribute which has a specific value. Find elements with a specific value for a specific attribute Here's an example where we find elements with a specific value:
Test 2
Test 3
Link 1The selector simply tells jQuery to find all links (the a elements) which has a target attribute that equals the string value "_blank" and then append the text "[new window]" to them. But what if you're looking for all elements which don't have the value? Inverting the selector is very easy: $("a[target!='_blank']").append(" [same window]"); The difference is the != instead of =, a common way of negating an operator within many programming languages. And there's even more possibilities: Find elements with a value which starts with a specific string using the ^= operator:
Link 2
Link 3
$("input[name^='txt']").css("color", "blue");Find elements with a value which ends with a specific string using the $= operator:
$("input[name$='letter']").css("color", "red");Find elements with a value which contains a specific word:
$("input[name*='txt']").css("color", "blue");
$("#divTest")An example of it in use:
Now, while there is only a single element that matches our query above, you should be aware that the result is a list, meaning that it can contain more than one element, if the query matches more than one. A common example of this is to match all elements which uses one or several CSS classes. The .class selector Elements with a specific class can be matched by writing a . character followed by the name of the class. Here is an example:
$("a")Or all div tags like this:
$("div")If you use a multi-element selector, like the class selector we used in the previous example, and we know that we're looking for elements of a specific type, it's good practice to specify the element type before the selector. Not only is it more precise, it's also faster for jQuery to process, resulting in more responsive sites. Here is a re-written version of the previous example, where we use this method:
$("span.bold").css("font-weight", "bold");This will match all span elements with "bold" as the class. Of course, it can be used with ID's and pretty much all of the other selectors as well. Selectors can do much more for you though. Read on for more cool examples.
The first parameter is the URL, which is just content.html. The second parameter is more interesting. It's a callback function, which jQuery calls if the page request succeeds. The first callback parameter is simply the content of the page requested, while the second callback parameter is the textual status of the request. You can of course request a simple HTML page, like in the example above, but normally the reason for using a GET or a POST request is that you wish to pass in some parameters, which is then processed by the server, for instance with a piece of PHP, ASP or ASP.NET code, and then return the result. jQuery can take a map of GET or POST parameters, which we will try in the following example, where we use the post() method: Try this example
This example is much like the first one, but we make the POST request to another page, in this example a PHP page, and as the second parameter, we pass in a map of POST parameters. The map is constructed of two parameters, a name and an age. If we had used a GET request instead of a POST request (POST requests doesn't take parameters from the URL like GET does), the above code would actually have corresponded to requesting an URL like this in your browser: test_get.php?name=John Doe&age=42 The PHP script can then read the parameters, process them and return a result. The script on our server simply takes the two values and creates a string like " is years old" and then returns it, which you can see if you test the example above.
empty() div remove() divThe first link will call the empty() method on our test div, removing all the child elements. The second link will remove the entire div, including any child elements. Pretty simple stuff. The remove() method comes with one optional parameter, which allows you to filter the elements to be removed, using any of the jQuery selector syntaxes. You could of course achieve the same simply by doing the filtering in your first selector, but in some situations, you may be working on a set of already selected elements. Check out this example of it in use:Bold text Italic text
remove() more boldWe start out by selecting all bold tags inside our test div. We then call the remove() method on the selected elements, and pass in the .more filter, which will make sure that we only get elements which uses the class "more". As a result, only the last two bold texts are removed. You can of course use even more advanced selectors as a filter too. Have a look at the "Selectors" topic of this tutorial for inspiration.Bold text
More bold text
Even more bold text
Before AfterDepending on which of the two links you click, an italic or a bold tag will be inserted before or after each input element on the page using the "test1" class. Just like with append() and prepend(), both after() and before() allows you to use HTML strings, DOM elements and jQuery objects as parameters and an infinite amount of them as well. We'll demonstrate that in the next example: Try this example
Insert elementsIn this example, we create a jQuery object, an HTML string and a JavaScript DOM element, and then we use the after() method to insert all of them after our span tag. Of course, the before() method could have been used in exactly the same way. There are variations of the before() and after() methods, called insertBefore() and insertAfter(). They do pretty much the same, but they do it the other way around, so instead of calling them on the elements you wish to insert data before or after, with a parameter of what is to be inserted, you do the exact opposite. Which method to use obviously depends on the situation, but here's an example showing you how to use them both: Try this example
Hello world?
Insert elemenetsIn this example, we insert the items before the span tag, but you could of course do the exact same using after() and insertAfter(), if you wish to insert after the target elemenet. As you can see, the result is the same - only the order of what we do differs.
Hello world?
Append PrependWe have to links: The first will append an item to the list, meaning that the new item will be inserted as the last item. The other link will prepend a link to the list, which means that the new item will be inserted as the first item of the list. In this example, we simply insert a piece of HTML, but we could have generated the new items with jQuery as well, or created it through regular JavaScript code and DOM elements. In fact, both the append() and the prepend() method takes an infinite amount of new elements as parameters. In the next example, we will demonstrate this as well as the ability to add elements in various forms:
- Existing item
- Existing item
Append itemsAs you can see, item1 is a jQuery generated element, item2 is a simple HTML string and item3 is a JavaScript DOM generated element. They are all appended to the list using the same call and of course this would have worked for the prepend() method too. There are variations of the append() and prepend() methods, called appendTo() and prependTo(). They do pretty much the same, but they do it the other way around, so instead of calling them on the elements you wish to append/prepend to, with a parameter of what is to be appended/prepended, you do the exact opposite. Which to use obviously depends on the situation, but here's an example showing you how to use them both:
Prepend itemsIn this example, we prepend the items, but you could of course do the exact same using append() and appendTo(). As you can see, the result is the same - only the order of what we do differs.
.bold { font-weight: bold; } .blue { color: blue; }In the following example we will use three of the most interesting class related methods: hasClass(), which checks if one or several elements already has a specific class defined, addClass(), which simply adds a class name to one or several elements and the removeClass() methods, which will.... well, you've probably already guessed it.
Toggle classThe example is actually very simple. When the link is clicked, we send the link itself (this) as a parameter to the ToggleClass() method that we have defined. In it, we check if the sender already has the "bold" class - if it has, we remove it, otherwise we add it. This is a pretty common thing to do, so obviously the jQuery people didn't want us to write an entire three lines of code to it. That's why they implemented the toggleClass() method, with which we can turn our entire example above into a single line of code:
Toggle classOf course, we can select multiple elements, where we can add or remove multiple classes, as well. Here's an example of just that:
First we select the span and the b tag, which we add a single class to: the bold class. Then we select the div tag, which we add two classes to, separated by a space: The bold and the blue class. The removeClass() methods works just the same way, allowing you to specify several classes to be removed, separated with a space.Test 1
Test 2Test 3
Google LinkIn this example, we get the value of the "href" attribute of our link and then show it to the user. To change an attribute, we simply specify an extra parameter:
Google LinkThis will change the link to point to the British version of Google. The attr() method can also take a map of name/value pairs, for setting multiple attributes at the same time. Here we set both the href and the title attributes simultaneously:
Google LinkThe attr() method also supports the special overload where the value parameter is instead a callback function, allowing you to access the index of the element selected as well as the existing attribute value. Here's an example of just that:
Google.comWe simply change all the Google links to point to the Image search instead of the default page, by adding an extra parameter to the href attribute. In this example we don't really use the index parameter, but we could have if we needed it, to tell us which index in the list of elements selected we're currently dealing with.
Google UK
Google DE
So a call to one of these methods with no parameters will simply return the desired property. If we want to set the property instead, we simply specify an extra parameter. Here's a complete example:Test
And that's how easy it is to set text, HTML and values. These three functions comes with one overload more though, where you specify a callback function as the first and only parameter. This callback function will be called with two parameters by jQuery, the index of the current element in the list of elements selected, as well as the existing value, before it's replaced with a new value. You then return the string that you wish to use as the new value from the function. This overload works for both html(), text() and val(), but for the sake of simplicity, we only use the text() version in this example:
We start out with three similar paragraph elements, which text is their only difference. In the jQuery code, we select all of them and then use the special version of the text() method to replace their current text with a newly constructed text, based on the two parameters that jQuery provides for us: The index of the current element as well as its current text. This new text is then returned to jQuery, which will replace the current text with the new one.Paragraph 1
Paragraph 2
Paragraph 3
Show box StopTo make the example a bit more compact, I have used inline calls in the onclick events of the two links. When you click the first link, the slideDown() method is used on our div element, starting a slow slide down. A click on the second link will kill the current animation being performed on the selected element. This is the default behavior of the stop() method, but two optional parameters allows us to do things differently. The first parameter specifies whether the animation queue should be cleared or not. The default is false, which means that only the active animation will be stopped, allowing any queued animations to be performed afterwards. The following example will demonstrate that:Hello, world!
Show box Stop Stop all ResetWe have added a second animation to the "Show box" link. This will slowly slide down the box, and once done, slide it up again. The queue system makes sure that these steps are performed in sequence. Now, click the "Reset" link to have the box hidden again and then click the "Show box" link once more, followed by a click on "Stop". You will see that the first animation is stopped, allowing for the second animation to be executed. However, if you try again and click on the "Stop all" instead, the true value passed will make sure that the entire queue is cleared and that all animation on the element is stopped. The second parameter tells jQuery whether you would like for it to just stop where it is, or rush through the animation instead, allowing for it to finish. This makes a pretty big difference, because as you can see from the first example, once you hit stop, the default behavior is to simply stop the animation where it is and leave it like that. The following example will show you the difference:Hello, world!
Show box Stop Stop but finish ResetTry the two "Stop" variations - the first will stop immediately, while the second one will rush the animation to finish.Hello, world!
The first, and only required, parameter of the animate function is a map of the CSS properties that you wish to have altered. In this case, we have an absolutely positioned div element, which we tell jQuery to move until it has reached a left property of 200 pixels. The second parameter allows you to specify the duration of the animation in milliseconds or as "slow" or "fast" which is the same as 600 or 200 ms. With this, we can slow down the above example as much as we want:
As the third parameter, we can specify a callback function to be called once the animation is done. This can be very useful for performing a number of different animations in a row. For instance, check out this example:
It might seem a bit overwhelming, but what we do is that we call the animate method and ask for the left property of our test "div" to be animated until it reaches a left of 100 pixels. We want it to take 1 second (1000 milliseconds) and once it completes, we wish for a new animation to start, which moves it back to 20 pixels within half a second, and as soon as THAT animation is done, we move it a bit right again, so that it now has a left property of 50 pixels. However, since jQuery comes with queue functionality for animations, you can actually achieve the above example in a much simpler manner. This however only applies when you want a set of animations to performed after each other - if you want to do something else when an animation is complete, the above example will still be the way to go. Here's the queue version:
Show Content
Download Content Example | |
function contentDisp() { $.ajax({ url : "textContent.php", success : function (data) { $("#contentArea").html(data); } }); }3. Content of the text file Here is the content of the text file: Welcome to RoseIndia.Net jQuery Tutorials Learn how you can do a lot of work with small code. jQuery is here to help us in achieving high result with less coding. jQuery is great!!!! 4. Program screen shot Open your browse and type http://localhost/displayContent.html. Your browser should look like:
If you have the content file in another directory, or if you have named it differently, you will have to change the parameter for the load method accordingly. This is all it takes to load content from an external file with jQuery and the load method. A pretty cool trick is that you can actually pass a selector along with the URL, to only get a part of the page. In the first example, we loaded the entire file, but in the following example, we will only use the div, which contains the first sentence: Try this example
As you can see, we simply append a standard jQuery selector to the parameter, after the URL, separated with a space. This causes jQuery to select the content out and only pass the matched part(s) back to the container. You can use any jQuery selector type to pull off this trick, which makes it pretty powerful. The load method can take two extra parameters: A set of querystring key/value pairs, and a callback function which will be executed when the load method finishes, no matter if it succeeds or fails. Here is an example where we use the callback function to inform about the result. Normally, you would likely only show a message if the method fails, but to illustrate how it works, we do it if the method fails as well. I make sure that it fails for the example, by requesting a file which doesn't exist: Try this example
As you can see, the callback function specifies 3 parameters, which jQuery will fill in for you. The first parameter will contain the resulting content if the call succeeds. The second parameter is a string which specifies the status of the call, e.g. "success" or "error". You can use it to see if the call was successful or not. The third parameter is the XMLHttpRequest object used to perform the AJAX call. It will contain properties which you can use to see what went wrong and many other things.
jQuery load HTML test