24
JQUERY "WRITE LESS, DO MORE" What is it, why use it, how to use it

JQUERY "WRITE LESS, DO MORE" What is it, why use it, how to use it

Embed Size (px)

Citation preview

JQUERY"WRITE LESS, DO MORE"What is it, why use it, how to use it

jQuery – "Write Less, Do More"

jQuery is a JavaScript library, collection of functions that extends JavaScript's capabilities

What would take 20 lines or more of JavaScript can be achieved in just two or three lines of jQuery

The same code runs in all browsers—there's no need to write special code for Internet Explorer

Uses HTML elements and CSS selectors, leveraging knowledge that most web designers already have

Simple Hide-Show Content

before user clicks Item One after user clicks Item One

jQuery code<script>$(function() {

$('h2 + p').hide();$('h2').click(function(e) {

var para = $(this).next('p');para.toggle();if (para.css('display') == 'none') { $(this).css('background-image', 'url(images/arrow-

r.png)');} else { $(this).css('background-image', 'url(images/arrow-

down.png)');}

}) .css('cursor', 'pointer');});</script>

Notice the use of the jQuery

symbol, $You can also "call" for jQuery by its name instead of using $

<script>function init() {

var headings = document.getElementsByTagName('h2'),

dom = headings[0].addEventListener, len = headings.length,i, para;

for (i=0; i < len; i++) {para = getNextSibling(headings[i]);para.style.display = 'none';if (dom) {

headings[i].addEventListener('click', toggle, false);

headings[i].addEventListener('mouseover', showHand, false);} else {

headings[i].attachEvent('onclick', toggle);}

}function getNextSibling(elem) {

var temp = elem.nextSibling;while (temp.nodeType !=1 &&

temp.nextSibling != null) {temp =

temp.nextSibling;}return temp;

}function toggle(event) {

var evt, tgt, para;evt = event ? event : window.event;tgt = evt.target || evt.srcElement;para = getNextSibling(tgt);

JavaScript code

if (para.style.display == 'none') {para.style.display = 'block'; tgt.style.backgroundImage = 'url(images/arrow-

down.png)';} else {

para.style.display = 'none';tgt.style.backgroundImage =

'url(images/arrow-r.png)'; }}function showHand(event) {

var evt, tgt;evt = event ? event : window.event;tgt = evt.target || evt.srcElement;tgt.style.cursor = 'pointer';

}}window.onload = init;</script>

Why less code with jQuery? jQuery ihas built in widgets like tabs, menus,

accordions jQuery simplifies targeting of elements

Does not traverse the Document Object Model (DOM)

Instead it uses HTML and CSS to target content

What do you need to know? HTML tags and how they are hierarchically arranged, i.e.

nesting of tags that creates parent child relationships CSS selectors: tag, descendant, class, id CSS rules, for example

background-color position with top, bottom, right, left display – inline, inline-block, block, none color margin

"little " bit of programming experience; the more the better

Step 1: Include jQuery core library

<!-- from CDN --><script src="http://code.jquery.com/jquery-latest.min.js"></script><!-- from your domain --><script type="text/javascript" src="scripts/jquery-1.9.1.js"></script>

Script tag placed in Page Head Can be linked to Content Delivery Network, may be faster for end

user if already cached File can be downloaded from www.jquery.com to your domain and

linked from that location

1.9.1 may not be the most current version;you can also use the minified version of the file

Step2: Create a jQuery document ready function

<script type="text/javascript">$('document').ready(function() {

alert("The page just loaded!"); //tell user with popup

}); //end of ready function</script>

Placed in Page Head Runs when page loads

<script type="text/javascript">$(function() {

alert("The page just loaded!");

}); //end of ready function</script>

Shorthand Version

Alternative to alert:console.log('Page loaded');

In Chrome open the console pane usingWin ctrl+shift+j or Mac cmd+opt+j

Step3: Try out a jQuery Selector & Method

<script type="text/javascript">$(function() {

$('p').css("border", "3px solid red");

}); //end of ready function</script>

SCRIPT

<body><ul id="list1">

<li class="a">item 1</li><li class="a">item 2</li><li class="b">item 3</li><li class="b">item 4</li>

</ul><p class="a">This is paragraph 1</p><p>This is paragraph 2</p><p class="b">This is paragraph 3</p><p>This is paragraph 4</p></body>

BASIC HTML

<style>.a (color: navy;}.b {color: maroon;}

</style>

STYLES

Use console to quick-test code You can type jQuery code directly into the

browser console Just type filter selectors and browser will return an

array of all elements it found matching that filter Chrome: Opening the console

View menu > Developer > JavaScript Console Win ctrl+shift+j or Mac cmd+opt+j

Firefox: Opening Firebug to access console View menu > Firebug (or press F12) Developer Tools > Open Firebug

jQuery selector Used to select/target content elements Syntax

$('selector') Selector can be any combination of html

elements and css selectors

jQuery selector examples$('document')$('h2')$('ul li a')$('h2+p') adjacent siblings

$('#wrapper')$('.myclass')$('p.b') paragraphs w class b

$('li:first-child')

$('p:first')$('p:last')

$('#lcol p, #rcol p')$('tr:even')$('tr:odd')$('form:checked') form elems w checked attribute

$('input:text') input elems w text attribute

a[href$='.pdf'] href attribute's value ends with .pdf

jQuery method Action carried out on selected/targeted

content elements Syntax

$('selector').methodname(parameters); Parameters

Vary for each method May need to be enclosed in quotes and/or curly

braces

Useful jQuery methods next([selector]) prev([selector]) attr(attributeName) attr(attributeName, value) css(propertyName) css(propertyName, value) addClass(className) removeClass([className]) toggleClass(className) html(content)

before(content) after(content) append(content) hide([duration]) show([duration]) toggle([duration]) fadeIn fadeOut FadeTo slideUp([duration]) slideDown([duration]) slideToggle([duration]) animate(properties, options)

jQuery method examples, 1$("h2").css("color", "blue"); $("p:first").css("border", "3px solid red");

$('div').css({fontSize: '13px', background: '#f60'});$("li a[href$='.pdf']").after("<img src='images/pdf_icon.gif'>");$("a").attr("target", "_blank");$("a").removeAttr("href"); $("p:last").text("this is the last paragraph");$("table#theList tr:even").addClass("stripe1"); $("img").attr({ src: "images/Spring.jpg", alt: "spring" });

jQuery method examples-animate

$('nav').animate({'height':'0px'},500);$("div").animate({left:'250px'},2000);$('img.prev').animate({'opacity':0},1000);$('#div').animate({width:'100px',opacity:'0.8'},"slow");

Chaining jQuery methods One of the biggest time-saving features of

jQuery is the ability to chain methods. You can apply multiple methods to the same

selected element(s) using dot notation.

$('body').append('<p>This paragraph was added dynamically.</p>') .addClass('reverse');$("#p1").css("color","red").slideUp(2000).slideDown(2000);$("#menu").fadeIn("fast").addClass("active").css("marginRight", "10px");

Important points about Chaining It makes your code short and easy to manage. It gives better performance – because jQuery

has to find the element only once to perform multiple actions.

The chain starts from left to right; so left most will be called first and so on.

BTW, chaining also works for events which we will cover next.

jQuery events Action resulting from user or browser

interaction with selected/targeted content elements

Syntax$('selector').eventname(function(){

//what the event handler is to do});

Useful jQuery events ready(handler) unload(handler) error(handler) click(handler) toggle(handlerEven, handlerOdd) dblclick(handler) mouseenter(handler) mouseover(handler) mouseout(handler) hover(handlerIn, handlerOut)

jQuery event example – hover$("#image_list img").hover(

function() {

alert("The mouse pointer has moved into an img element");

},

function() {

alert("The mouse pointer has moved out of an img element");

}

); // end hover

jQuery event examples – click$("#showbtn").click(function() {

$("#theDiv").show("normal");

});

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

$("#theDiv").hide("normal");

});

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

$("#theDiv").toggle("slow");

});

The this selection keyword When working inside of a jQuery function you

may want to select the element in which was referenced inside of the original selector.

In this code example the this keyword refers to the element selected in the current handler.

$('div').click(function(event){ $(this); //here this refers to the div that was clicked});