jquery besic

40
jQuery Syeful Islam

Upload: md-syeful-islam

Post on 20-Jul-2015

167 views

Category:

Technology


0 download

TRANSCRIPT

jQuerySyeful Islam

Training Covered...

• What is jQuery?

• Why jQuery?

• How include jQuery in your web page

• Creating and manipulating elements

• Events

• Animations and effects

• Talking to the server

• jQuery UI

• Writing plugins

• Breaking news around new releases

• Using the CDN

What is jQuery?

•jQuery is an Open-Source JavaScript framework that

simplifies cross-browser client side scripting.

• Animations

• DOM manipulation

• AJAX

• Extensibility through plugins

•jQuery was created by John Resig and released 2006

Why jQuery?....

• Lightweight Footprint - Only 32kB minified and gzipped. Can

also be included as an AMD module.

• CSS3 Compliant- Supports CSS3 selectors to find elements as

well as in style property manipulation.

• Cross-Browser - IE, Firefox, Safari, Opera, Chrome, and more

• Features.

• Select and manipulate HTML

• Manipulate CSS

• JavaScript Effects and animations

• HTML DOM traversal and modification

• AJAX

• Utilities

• The heart of jQuery is “Find something then Do something”

Why jQuery?

• Example 1 -Hide an element with id "textbox“

//javascript

document.getElementById('textbox').style.display = "none";

//jQuery

$('#textbox').hide();.

• Example 2 -Create a <h1> tag with "my text“

//javascript

var h1 = document.CreateElement("h1");

h1.innerHTML = "my text";

document.getElementsByTagName('body')[0].appendChild(h1);

//jQuery

$('body').append( $("<h1/>").html("my text") ;

Enable jQuery in your page

• jQuery can be downloaded from jQuery.com.<head><script src="jquery-1.11.1.min.js"></script></head>

• Without downloading it can be included from CDN

• Google CDN:

src=http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js

• Microsoft CDN:

src=http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js

• It’s recommend to use the hosted jQuery from Google or Microsoft.

Browser Support

Internet

ExplorerChrome Firefox Safari Opera iOS Android

jQuery

1.x6+

(Current -

1) or

Current

(Current -

1) or

Current

5.1+

12.1x,

(Current -

1) or

Current

6.1+ 2.3, 4.0+

jQuery

2.x9+

Getting Started

Example:<!DOCTYPE html>

<html>

<head>

<script

src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">

</script>

<script>

$(document).ready(function(){

$(“#hideme").click(function(){

$(this).hide();

});

});

</script>

</head>

<body>

<p id=“hideme”>If you click on me, I will disappear.</p>

</body>

• Include jQuery in the

source file

• Define jQuery functions

• Save this file as

index.htm

• Try it!

Example : A Closer Look

• $(“#hideme") selects the element with ID hideme

• click() binds a click event to selected element

• The function executes when the click event is

fired

<script>

$(document).ready(function(){

$(“#hideme").click(function(){

$(this).hide();

});

});

</script>

Element will be hidden when the element with ID hideme is clicked

jQuery Syntax

• The jQuery syntax is used to select HTML elements and perform some action on those element(s).

• Basic syntax: $(selector).action()

• A dollar ($) sign to define jQuery

• A (selector) to find HTML elements

• An action() to be performed on the element(s)

• Usually define functions only after the document is finished loading, otherwise elements may not be there.

$(document).ready(function(){

// jQuery functions go here...

});

jQuery Syntax Examples

• jQuery uses CSS syntax to select elements.

• $(this).hide()Demonstrates the jQuery hide() method, hiding the current HTML element.

• $("#test").hide()Demonstrates the jQuery hide() method, hiding the element with id="test".

• $("p").hide()Demonstrates the jQuery hide() method, hiding all <p> elements.

• $(".test").hide()Demonstrates the jQuery hide() method, hiding all elements with class="test".

jQuery Selectors

Syntax Description

$(this) Current HTML element

$("p") All <p> elements

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

$(".intro") All elements with class="intro"

$("#intro") The first element with id="intro"

$("ul li:first") The first <li> element of each <ul>

$("[href$='.jpg']") All elements with an href attribute that ends with ".jpg"

$("div#intro .head")All elements with class="head" inside a <div> element

with id="intro"

For a full reference please see:

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

Comparison

• Compare the following:What are the

advantages

of the jQuery

method?

$("a").click(function(){

alert("You clicked a link!");

});

<a href="#" onclick="alert(‘You clicked a link!')">Link</a>

• Separation of structure (HTML) and behavior (JS)

• We don’t need an onclick for every element

Example

<script>

$("button").click(function(){

$("h2").hide();

});

</script> What will this do?

What happens if

you have more

than one h2?

Try it!

CSS Selectors

• jQuery CSS Selectors

• jQuery CSS selectors can be used to change CSS properties for

HTML elements.

• The following example changes the background-color of all p

elements to yellow:

• Example

• $("p").css("background-color","yellow");

jQuery Events …• All the different visitor's actions that a web page

can respond to are called events. • moving a mouse over an element

• selecting a radio button

• clicking on an element

Mouse Events Keyboard Events Form Events Document/Window Events

click keypress submit load

dblclick keydown change resize

mouseenter keyup focus scroll

mouseleave blur unload

jQuery Events

Event 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

http://www.w3schools.com/jquery/jquery_ref_events.asp Reference

Example

<script>

$(document).ready(function(){

$("#p1").mouseenter(function(){

alert("You entered p1!");

});

});

</script>

What action will be

executed when

mouse enter on

element with id p1??

Try it!

$("p").click(function(){

// action goes here!!

});

Manipulating CSS

CSS 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

full jQuery CSS reference: http://www.w3schools.com/jquery/jquery_ref_css.asp

For more on the css function, see : http://api.jquery.com/css/

Example

<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>

Example

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>

jQuery Effects

Function 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

$(selector).fadeToggle() To stop an animation or effect before it is finished.

Hide, Show, Toggle, Slide, Fade, and Animate element in jQuery effect.

Example

<script>

$("#flip").click(function(){

$("#panel").slideToggle("slow");

});

</script>

Create a toggle button

that shows/hides

paragraph lemon.

Example

<script>

$(document).ready(function(){

$("button").click(function(){

$("div").animate({left:'250px'});

});

});

</script>

create custom

animations. for html

element div

Manipulating HTML …

• Set and get Content and Attributes:

• 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

• Add Elements

• 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

Example

<script>

$(document).ready(function(){

$("button").click(function(){

$("#w3s").attr("href","http://www.w3schools.com/jquery");

});

});

</script>

change (set) the value of

the href attribute in a link

Example

<script>

$(document).ready(function(){

$("#btn1").click(function(){

$("p").append(" <b>Appended text</b>.");

});

$("#btn2").click(function(){

$("ol").append("<li>Appended item</li>");

});

});

</script>

inserts content AT THE

END of the selected

HTML elements.

Manipulating HTML …

• Remove Elements:• remove() - Removes the selected element (and its child

elements)

• empty() - Removes the child elements from the selected element

• Get and Set CSS Classes• addClass() - Adds one or more classes to the selected

elements

• removeClass() - Removes one or more classes from the selected elements

• toggleClass() - Toggles between adding/removing classes from the selected elements

• css() - Sets or returns the style attribute.

Example

<script>

$(document).ready(function(){

$("button").click(function(){

$("#div1").remove();

});

});

</script>

remove elements and

content.

Example

<script>

$(document).ready(function(){

$("button").click(function(){

$("h1,h2,p").addClass("blue");

$("div").addClass("important");

});

});

</script>

Add class attributes to

different elements.

Manipulating HTML ….

• jQuery - Dimensions

• width()

• height()

• innerWidth()

• innerHeight()

• outerWidth()

• outerHeight()

Example

<script>

$(document).ready(function(){

$("button").click(function(){

var txt="";

txt+="Width of div: " + $("#div1").width() + "</br>";

txt+="Height of div: " + $("#div1").height();

$("#div1").html(txt);

});

});

</script>

Display di width and

height.

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

Manipulating HTML

Function 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

$(selector).fadeToggle() To stop an animation or effect before it is finished.

Hide, Show, Toggle, Slide, Fade, and Animate element in jQuery effect.

Example 10

<script>

$("#btnReplace").click(function(){

$("#lemon").html("Lollipop soufflé ice

cream tootsie roll donut...");

});

</script>

Replace text in

paragraph lemon when

btnReplace is clicked.

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 Description

URL 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

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

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" div

With the output of the PHP script

Ajax POST

ajax.php

So I hope you now say too...

Resources

• http://jquery.com/

• http://www.w3schools.com/jquery

• http://jqueryui.com/

Md. Syeful Islam

Sr. Software Engineer

Samsung R&D Institute Bangladesh

Email: [email protected]

Skype: syeful_islam