34
Introduction to jQuery

Introduction to jQuery

  • Upload
    efrem

  • View
    49

  • Download
    10

Embed Size (px)

DESCRIPTION

Introduction to jQuery. What is jQuery ?. a lightweight, "write less, do more", JavaScript library. The purpose is to make it much easier to use JavaScript. - PowerPoint PPT Presentation

Citation preview

Page 1: Introduction to  jQuery

Introduction to jQuery

Page 2: Introduction to  jQuery

What is jQuery?

• a lightweight, "write less, do more", JavaScript library.• The purpose is to make it much easier to use

JavaScript.• takes a lot of common tasks that require many lines

of JavaScript code to accomplish, and wraps them into methods that can be called with a single line of code.

• simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.

Page 3: Introduction to  jQuery

What is jQuery?

• The jQuery library contains the following features:– HTML/DOM manipulation– CSS manipulation– HTML event methods– Effects and animations– AJAX– Utilities

Page 4: Introduction to  jQuery

Using jQuery

• several ways to start using jQuery on your web site:– Download the jQuery library from jQuery.com, use

as external library, reference in HTML head (relative path)

– Include jQuery from a CDN, like Google, also use as external library, reference (via HTTP) in HTML head

Page 5: Introduction to  jQuery

Downloading jQuery

• There are two versions of jQuery available for downloading:

• Production version - this is for your live website because it has been minified and compressed

• Development version - this is for testing and development (uncompressed and readable code)

Page 6: Introduction to  jQuery

Downloading jQuery

• Both versions can be downloaded from jQuery.com.

• The jQuery library is a single JavaScript file, and you reference it with the HTML <script> tag (notice that the <script> tag should be inside the <head> section):

• <head><script src="jquery-1.10.2.min.js"></script></head>

Page 7: Introduction to  jQuery

Alternatives to Downloading

• If you don't want to download and host jQuery yourself, you can include it from a CDN (Content Delivery Network).

• Both Google and Microsoft host jQuery.

Page 8: Introduction to  jQuery

Google CDN• <head>

<script src=" //ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script></head>

Page 9: Introduction to  jQuery

Hello World

• Activity 1– hello1.html – local scripts– hello2.html – Google CDN

Page 10: Introduction to  jQuery

jQuery Syntax

• The jQuery syntax is tailor made for selecting HTML elements and performing some action on the element(s).

• Basic syntax is: $(selector).action()– A $ sign to define/access jQuery– A (selector) to "query (or find)" HTML elements– A jQuery action() to be performed on the

element(s)

Page 11: Introduction to  jQuery

jQuery Syntax

• 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".

Page 12: Introduction to  jQuery

The Document Ready Event

• to prevent any jQuery code from running before the document is finished loading (is ready).

• $(document).ready(function(){

// jQuery methods go here...

});

Page 13: Introduction to  jQuery

The Document Ready Event

• Good practice to wait for the document to be fully loaded and ready before working with it.

• Some examples of actions that can fail if methods are run before the document is fully loaded:– Trying to hide an element that is not created yet– Trying to get the size of an image that is not

loaded yet

Page 14: Introduction to  jQuery

The Document Ready Event

• Tip: The jQuery team has also created an even shorter method for the document ready event:

• $(function(){

// jQuery methods go here...

});

Page 15: Introduction to  jQuery

jQuery Selectors – activity 2

• jQuery selectors allow selection and manipulation of HTML element(s).

• Enable to find elements based on their id, classes, types, attributes, values of attributes and much more.

• It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.

• All type of selectors in jQuery, start with the dollar sign and parentheses: $().

Page 16: Introduction to  jQuery

Example – element selector

• select all <p> elements on a page like this:– $("p")

• When a user clicks on a button, all <p> elements will be hidden:– $(document).ready(function(){

$("button").click(function(){ $("p").hide(); });});

Page 17: Introduction to  jQuery

Example – #id selector

• #id selector uses the id attribute of an HTML tag to find the specific element.

• id should be unique within a page, so the #id selector is use to find a single, unique element– $(document).ready(function(){

$("button").click(function(){ $("#test").hide(); });});

Page 18: Introduction to  jQuery

Example – .class Selector

• finds elements with a specific class – by writing a period character, followed by the name of the class - $(".test")– $(document).ready(function(){

$("button").click(function(){ $(".test").hide(); });});

Page 19: Introduction to  jQuery

More Examples of jQuery SelectorsSyntax Description

$("*") Selects all elements

$(this) Selects the current HTML element

$("p.intro") Selects all <p> elements with class="intro"

$("p:first") Selects the first <p> element

$("ul li:first") Selects the first <li> element of the first <ul>

$("ul li:first-child") Selects the first <li> element of every <ul>

$("[href]") Selects all elements with an href attribute

$("a[target='_blank']") Selects all <a> elements with a target attribute value equal to "_blank"

$("a[target!='_blank']") Selects all <a> elements with a target attribute value NOT equal to "_blank"

$(":button") Selects all <button> elements and <input> elements of type="button"

$("tr:even") Selects all even <tr> elements

$("tr:odd") Selects all odd <tr> elements

Page 20: Introduction to  jQuery

Important Functions

• $().parseHTML('); //createElement• $().html(); //get or set element• $().val(); //get text value• $().append(); //append text or html• $().attr(); //get or set attribute

Page 21: Introduction to  jQuery

jQuery EventsEvent Method Description

$(selector).click(function) Invokes a function when the selected elements are clicked

$(selector).dblclick(function) Invokes a function when the selected elements are double-clicked

$(selector).focus(function) Invokes a function when the selected elements receive the focus

$(selector).mouseover(function) Invokes a function when the mouse is over the selected elements

$(selector).keypress(function) Invokes a function when a key is pressed inside the selected elements

For a full jQuery event reference, please see jQuery Events Reference

Page 22: Introduction to  jQuery

<script> $("#lemon").mouseover(function(){ $(this).append(" Cookie! ");

});</script>

Append text to paragraph lemon on mouseover

<p id='lemon'>Lemon drops biscuit chocolate…</p>

Page 23: Introduction to  jQuery

Manipulating CSSCSS Properties Description

$(selector).css(propertyName) Get the style property value of the first selected element

$(selector).css(propertyName,value) Set the value of one style property for selected elements

$(selector).css({properties}) Set multiple style properties for selected elements

$(selector).addClass(class) Apply style class to the selected elements

For a full jQuery CSS reference, please see jQuery CSS Methods ReferenceFor more on the css function, see http://api.jquery.com/css/

Page 24: Introduction to  jQuery

<script> $("#btnColor").click(function(){ $("#lemon").addClass("blue"); });</script>

Change color of paragraph lemon when btnColor is clicked

<style type="text/css">.red{

color:red;}.blue{

color:blue;}

</style>

Page 25: Introduction to  jQuery

Display the color of the paragraph lemon when

btnColorCheck is clicked.

What color is the paragraph?

<script>$("#btnColorCheck").click(function(){ alert($("#lemon").css("color"));});

</script>

<p id='lemon'>Lemon drops biscuit chocolate…</p>

Page 26: Introduction to  jQuery

<script>$("p").dblclick(function(){

$(this).css("background-color", "yellow");});

</script>

Highlight (background-color = yellow) any paragraph that is double-clicked

Page 27: Introduction to  jQuery

jQuery EffectsFunction Description$(selector).hide() Hide selected elements

$(selector).show() Show selected elements

$(selector).toggle() Toggle (between hide and show) selected elements

$(selector).slideDown() Slide-down (show) selected elements$(selector).slideUp() Slide-up (hide) selected elements

$(selector).slideToggle() Toggle slide-up and slide-down of selected elements

$(selector).fadeIn() Fade in selected elements$(selector).fadeOut() Fade out selected elements

$(selector).fadeTo() Fade out selected elements to a given opacity

$(selector).fadeToggle() Toggle between fade in and fade out

Page 28: Introduction to  jQuery

<script> $("#btnToggle").click(function(){ $("#lemon").slideToggle("slow"); });</script>

Create a toggle buttonthat shows/hides paragraph lemon.

<p id='lemon'>Lemon drops biscuit chocolate…</p>

Page 29: Introduction to  jQuery

<script> $("#btnFade").click(function(){ $("#lemon").fadeTo("slow", 0.5); });</script>

Fade paragraph lemon to 50% opacity when

btnFade is clicked.

<p id='lemon'>Lemon drops biscuit chocolate…</p>

Page 30: Introduction to  jQuery

Manipulating HTML

Function Description

$(selector).html(content) Changes the (inner) HTML of selected elements

$(selector).append(content) Appends content to the (inner) HTML of selected elements

$(selector).after(content) Adds HTML after selected elements

For a full jQuery HTML reference, please see jQuery HTML Methods Reference

Page 31: Introduction to  jQuery

<script> $("#btnReplace").click(function(){ $("#lemon").html("Lollipop soufflé ice

cream tootsie roll donut..."); });</script>

Replace text in paragraph lemon when btnReplace

is clicked.

<p id='lemon'>Lemon drops biscuit chocolate…</p>

Page 32: Introduction to  jQuery

Ajax• The jQuery $.post() method loads data from the server using an HTTP POST

request.• Syntax

$.post(URL, {data}, function(data){…});$.post("myScript.php", {name:txt}, function(result) {    $("span").html(result);  });

ajax.phpParameter DescriptionURL Required. Specifies the url to send the

request to.data Optional. Specifies data to send to the

server along with the request.function(data) •Optional. Specifies a function to run if

the request succeeds.data - contains the resulting data from the request

http://www.w3schools.com/jquery/ajax_post.asp

Page 33: Introduction to  jQuery

Ajax <?php

$id = $_POST['id'];

mysql_connect("localhost", "omuser", "omuser") or die("Error connecting"); mysql_select_db("om") or die("Error selecting DB"); $query = "SELECT * FROM items WHERE item_id = $id"; $result = mysql_query($query); if (mysql_num_rows($result) == 0) { echo "Product ID $id not found."; return; } $row = mysql_fetch_array($result); echo "<strong>Item ID:</strong> {$row['item_id']}<br>"; echo "<strong>Title:</strong> {$row['title']}<br>"; echo "<strong>Artist:</strong> {$row['artist']}<br>"; echo "<strong>Price:</strong> {$row['unit_price']}<br>";

Get this from the Ajax call

show_product.php

Page 34: Introduction to  jQuery

Ajax $('#show').click(function(){

var prodId = $('#id').val(); $.post(

"show_product.php",

{id:prodId},

function(result) { $('#detail').html(result); } ); });

When the button is clicked

Get the text box value

Name of the PHP script

The key/value to be passed

Update the "detail" divWith the output of the PHP script

Ajax POST

ajax.php