690 likes | 1.01k Views
JQuery. Web Technology. Derived from: http://www.w3schools.com/jquery/. What We Should Already Know. Before we start studying jQuery, we should have a basic knowledge of: HTML Cascading Style Sheet (CSS) Javascript. What is Jquery?.
E N D
JQuery Web Technology Derived from: http://www.w3schools.com/jquery/
What We Should Already Know • Before we start studying jQuery, we should have a basic knowledge of: • HTML • Cascading Style Sheet (CSS) • Javascript
What is Jquery? • jQuery is a lightweight, "write less, do more", JavaScript library. • The purpose of jQuery is to make it much easier to use JavaScript on our website. • jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.
JQuery Library • The jQuery library contains the following features: • HTML/DOM manipulation • CSS manipulation • HTML event methods • Effects and animations • AJAX • Utilities
Using jQuery Library • jQuery library is a single JavaScript file, and we can reference it with the HTML <script> tag • Notice that: the <script> tag should be inside the <head> section • Note: we can download jQuery library from jquery.com <head><script src="jquery-1.9.1.min.js"></script></head>
Using Online jQuery Library • If we don't want to download and host jQuery, we can include it from a CDN (Content Delivery Network). • To use jQuery from Google, use the following: • To use jQuery from Microsoft CDN, use: <head><script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script></head> <head><script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js"> </script></head>
JQuery Syntax • jQuery syntax is tailor made for selecting HTML elements and performing some action on the element(s). • Basic syntax is: $(selector).action() • $ sign is to define/access jQuery • selector is to "query (or find)" HTML elements • action() is function to be performed on the element(s) Examples: $(this).hide() -hides the current element. $("p").hide() -hides all <p> elements. $(".test").hide() -hides all elements with class="test". $("#test").hide() -hides the element with id="test".
The Document Ready Event • jQuery methods are inside a document ready event • This is to prevent any jQuery code from running before the document is finished loading (is ready). • We can use a shorter method for the document ready event as follow: $(document).ready(function(){ // jQuery methods go here...}); $(function(){// jQuery methods go here...});
Element Selector • The jQuery element selector selects elements based on their tag names. • We can select all <p> elements on a page like this: • Example: • When a user clicks on a button, all <p> elements will be hidden: $("p") $(document).ready(function(){ $("button").click(function(){$("p").hide(); });});
The #id Selector • We should use #id selector when we want to find a single, unique element in the page. • To find an element with a specific id, write a hash character, followed by the id of the element: • Example: • When a user clicks on a button, the element with id="test" will be hidden: $("#test") $(document).ready(function() { $("button").click(function() { $("#test").hide(); });});
The .class Selector • To find elements with a specific class, write a period character, followed by the name of the class: • Example: • When a user clicks on a button, the elements with class="test" will be hidden: $(".test") $(document).ready(function(){ $("button").click(function(){$(".test").hide(); });});
Functions in a Separate File • If our website contains a lot of pages, and we want our jQuery functions to be easy to maintain, • we can put our jQuery functions in a separate .js file. • In addition, our code would look nicer and more tidy. <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script><script src="my_jquery_functions.js"></script></head>
JQuery Events • All the different visitor's actions that a web page can respond to are called events • An event represents the precise moment when something happens. • Examples: • moving a mouse over an element • selecting a radio button • clicking on an element The term "fires" is often used with events. Example: "The keypress event fires the moment we press a key".
DOM Events • The followings are some example DOM events:
click() • The function is executed when the user clicks on the HTML element. • The following example says: • When a click event fires on a <p> element; hide the current <p> element: $("p").click( function() { $(this).hide(); } );
dbclick() • dbclick() method attaches an event handler function to an HTML element. • The function is executed when the user double-clicks on the HTML element: $("p").dblclick( function() { $(this).hide(); } );
mouseenter() • mouseenter() method attaches an event handler function to an HTML element. • The function is executed when the mouse pointer enters the HTML element: $("#p1").mouseenter( function() { alert("You entered p1!"); } );
Other Mouse Events • mouseleave() • The mouseleave() method attaches an event handler function to an HTML element. • mousedown() • The mousedown() method attaches an event handler function to an HTML element. • mouseup() • The mouseup() method attaches an event handler function to an HTML element.
hover() • hover() method takes two functions and is a combination of the mouseenter() and mouseleave() methods. • The first function is executed when the mouse enters the HTML element, • The second function is executed when the mouse leaves the HTML element: $("#p1").hover( function() { alert("You entered p1!"); } , function(){ alert("Bye! You now leave p1!"); } );
focus() • focus() method attaches an event handler function to an HTML form field. • The function is executed when the form field gets focus: $("input").focus( function() { $(this).css("background-color","#cccccc"); } );
blur() • blur() method attaches an event handler function to an HTML form field. • The function is executed when the form field loses focus: $("input").blur( function() { $(this).css("background-color","#ffffff");});
jQuery hide() and show() $(selector).hide(speed, callback); $(selector).show(speed, callback); • Syntax: • Optional speed parameter can take the following values: "slow", "fast", or milliseconds. • Optional callback parameter is a function to be executed after the hide() or show() method completes. • With jQuery, we can hide and show HTML elements with the hide() and show() methods as examples below: $("#hide").click(function() { $("p").hide();});$("#show").click(function() { $("p").show();});
jQuery toggle() $(selector).toggle(speed,callback); • Syntax: • Optional speed values can be: "slow", "fast", or milliseconds. • Optional callback function is a function to be executed after toggle() completes. • We can toggle between hide() and show() methods with toggle() method. • Shown elements are hidden and hidden elements are shown: $("button").click( function() { $("p").toggle(); } );
The animate() Method • animate() method is used to create custom animations. • Required params defines CSS properties to be animated. • Optional speed specifies duration of the effect. It can take the following values: "slow", "fast", or milliseconds. • Optional callback is a function to be executed after the animation completes. $(selector).animate({params},speed,callback);
Example of animate() Method • The following example demonstrates a simple use of the animate() method; • it moves a <div> element to the left, until it has reached a left property of 250px: • This example uses multiple properties: $("button").click( function() { $("div").animate({left:'250px'});}); $("button").click(function() { $("div").animate( { left:'250px', opacity:'0.5', height:'150px', width:'150px' });});
animate() - Using Relative Values • It is also possible to define relative values • The value is then relative to the element's current value. • This is done by putting += or -= in front of the value: $("button").click( function() { $("div").animate( { left:'250px', height:'+=150px', width:'+=150px' }); } );
animate() - Using Pre-defined Values • We can even specify a property's animation value as "show", "hide", or "toggle": $("button").click( function() { $("div").animate( { height:'toggle' }); } );
animate() - Uses Queue Functionality • We can write multiple animate() calls after each other. • jQuery creates an "internal" queue with these method calls. • If we want to perform different animations after each other, we take advantage of the queue functionality: $("button").click(function() { var div = $("div"); div.animate({height:'300px',opacity:'0.4'}, "slow"); div.animate({width:'300px',opacity:'0.8'}, "slow"); div.animate({height:'100px',opacity:'0.4'}, "slow"); div.animate({width:'100px',opacity:'0.8'}, "slow");});
Example of Queue Functionality • This example first moves the <div> element to the right, and then increases the font size of the text: $("button").click( function() { var div=$("div"); div.animate( { left:'100px‘ }, "slow"); div.animate( { fontSize:'3em‘ }, "slow"); } );
stop() Method • Optional stopAll specifies whether also the animation queue should be cleared or not. • Default is false, which means that only active animation will be stopped, allowing any queued animations to be performed afterwards. • Optional goToEnd specifies whether or not to complete the current animation immediately. • Default is false. • So, by default, the stop() method kills current animation being performed on the selected element. $(selector).stop( stopAll, goToEnd);
Example of stop() Method • Following example demonstrates the stop() method, with no parameters: $("#stop").click( function() { $("#panel").stop(); } );
jQuery Callback Functions • JavaScript statements are executed line by line. • However, with effects, the next line of code can be run even though the effect is not finished. • This can create errors. • To prevent this, we can create a callback function. • A callback function is executed after the current effect is finished. • A typical syntax: $(selector).hide(speed, callback);
Example of Callback Functions • Example with callback • Example without callback $("button").click(function(){ $("p").hide("slow", function(){ alert("The paragraph is now hidden"); });}); $("button").click(function(){ $("p").hide(1000); alert("The paragraph is now hidden");});
Method Chaining • Chaining allows us to run multiple jQuery commands, one after the other, on the same element(s). • To chain an action, we simply append action to the previous one. • Following example chains together the css(), slideUp(), and slideDown() methods. • The "p1" element first changes to red, then it slides up, and then it slides down: $("#p1").css("color", "red").slideUp(2000).slideDown(2000);
Tip on Method Chaining • When chaining, line of code could become quite long. • However, jQuery is not very strict on the syntax; • we can format it like we want, including line breaks and indentations. • So, this also works just fine: • Note: • jQuery throws away extra whitespace and executes the lines above as one long line of code. $("#p1").css("color", "red") .slideUp(2000) .slideDown(2000);
Get/Set Content and Attributes • jQuery contains powerful methods for changing and manipulating HTML elements and attributes. • Three simple useful jQuery methods for DOM manipulation are: • text() - sets or returns the text content of selected elements • html()- sets or returns the content of selected elements (including HTML markup) • val() - sets or returns the value of form fields
Get Content and Value • The following example demonstrates how to get content with text() and html() methods: • The following example demonstrates how to get the value of an input field with val() method: $("#btn1").click(function() { alert("Text: " + $("#test").text());});$("#btn2").click(function() { alert("HTML: " + $("#test").html());}); $("#btn1").click(function() { alert("Value: " + $("#test").val());});
Get Attributes - attr() • attr() method is used to get attribute values. • The following example demonstrates how to get the value of the href attribute in a link: $("button").click( function() { alert($("#w3s").attr("href")); } );
Set Content and Attribute • The following example demonstrates how to set content with text(), html(), and val() methods: $("#btn1").click( function() { $("#test1").text("Hello world!"); } );$("#btn2").click( function() { $("#test2").html("<b>Hello world!</b>"); } );$("#btn3").click( function() { $("#test3").val("Dolly Duck"); } );
Callback Function for text(), html(), and val() • Callback function has two parameters: • index of the current element in the list of elements selected • and the original (old) value. • We can return string to use as new value from function. $("#btn1").click(function() { $("#test1").text(function(i, origText) { return "Old text: " + origText + " New text: Hello! (index: " + i + ")"; });});$("#btn2").click(function() { $("#test2").html(function(i, origText) { return "Old html: " + origText + " New html: <b>Hello!</b> (index: " + i + ")"; });});
Set Attributes - attr() • attr() method is also used to set/change attribute values. • The following example demonstrates how to change (set) the value of the href attribute in a link: $("button").click( function() { $("#w3s").attr("href", "http://www.w3schools.com/jquery"); } );
Set Multiple Attributes • attr() method also allows us to set multiple attributes at the same time. • The following example demonstrates how to set both the href and title attributes at the same time: $("button").click( function() { $("#w3s").attr( { "href" : "http://www.w3schools.com/jquery", "title" : "W3Schools jQuery Tutorial" }); } );
Callback Function for attr() • Callback function for attr() has two parameters: • the index of the current element in the list of elements selected • and the original (old) attribute value. • We can return string to use as new value from function. $("button").click( function() { $("#w3s").attr("href", function(i, origValue) { return origValue + "/jquery"; }); } );
Add New HTML Content • jQuery provides 3 methods to add new content: • append() - inserts content at the end of the selected elements • prepend() - inserts content at the beginning of the selected elements • after() - inserts content after the selected elements • before() - inserts content before the selected elements
Append and Prepend Methods • append() method inserts content AT THE END of the selected HTML elements. • prepend() method inserts content AT THE BEGINNING of the selected HTML elements. $("p").append("Some appended text."); $("p").prepend("Some prepended text.");
Add Several New Elements with append() and prepend() • Both append() and prepend() methods can take an infinite number of new elements as parameters. function appendText(){ var txt1 = "<p>Text.</p>"; // Create element with HTML var txt2 = $("<p></p>").text("Text."); // Create with jQuery var txt3 = document.createElement("p"); // Create with DOM txt3.innerHTML = "Text."; $("p").append(txt1, txt2, txt3); // Append the new elements}
after() and before() Methods • after() method inserts content AFTER the selected HTML elements. • before() method inserts content BEFORE the selected HTML elements. $("img").after("Some text after");$("img").before("Some text before");
Add Several New Elements With after() and before() • Both after() and before() methods can take an infinite number of new elements as parameters. function afterText(){ var txt1 = "<b>I </b>"; // Create element with HTML var txt2 = $("<i></i>").text("love "); // Create with jQuery var txt3 = document.createElement("big"); // Create with DOM txt3.innerHTML = "jQuery!"; $("img").after(txt1,txt2,txt3); // Insert new elements after img}
Remove Elements/Content • To remove elements and content, there are mainly two jQuery methods: • remove() - removes selected element (and its child elements) • empty() - removes child elements from selected element $("#div1").remove(); $("#div1").empty();