Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations

Presentation on theme: "JQUERY "WRITE LESS, DO MORE" What is it, why use it, how to use it."— Presentation transcript:

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

2 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

3 Simple Hide-Show Content before user clicks Item Oneafter user clicks Item One

4 jQuery code $(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');}); Notice the use of the jQuery symbol, $ You can also "call" for jQuery by its name instead of using $ Notice the use of the jQuery symbol, $ You can also "call" for jQuery by its name instead of using $

5 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]); = '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.srcElement; para = getNextSibling(tgt); JavaScript code if ( == 'none') { = 'block'; = 'url(images/arrow-down.png)'; } else { = 'none'; = 'url(images/arrow- r.png)';} } function showHand(event) { var evt, tgt; evt = event ? event : window.event; tgt = || evt.srcElement; = 'pointer'; } window.onload = init;

6 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

7 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

8 Step 1: Include jQuery core library  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 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

9 Step2: Create a jQuery document ready function $('document').ready(function() { alert("The page just loaded!"); //tell user with popup }); //end of ready function  Placed in Page Head  Runs when page loads $(function() { alert("The page just loaded!"); }); //end of ready function Shorthand Version Alternative to alert: console.log('Page loaded'); In Chrome open the console pane using Win  ctrl+shift+j or Mac  cmd+opt+j Alternative to alert: console.log('Page loaded'); In Chrome open the console pane using Win  ctrl+shift+j or Mac  cmd+opt+j

10 Step3: Try out a jQuery Selector & Method $(function() { $('p').css("border", "3px solid red"); }); //end of ready function SCRIPT item 1 item 2 item 3 item 4 This is paragraph 1 This is paragraph 2 This is paragraph 3 This is paragraph 4 BASIC HTML.a (color: navy;}.b {color: maroon;} STYLES

11 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

12 jQuery selector  Used to select/target content elements  Syntax $('selector')  Selector can be any combination of html elements and css selectors

13 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

14 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

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

16 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(" "); $("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" });

17 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");

18 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(' This paragraph was added dynamically. ').addClass('reverse'); $("#p1").css("color","red").slideUp(2000).slideDown(2000); $("#menu").fadeIn("fast").addClass("active").css("marginRight", "10px");

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

20 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 });

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

22 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

23 jQuery event examples – click $("#showbtn").click(function() { $("#theDiv").show("normal"); }); $("#hidebtn").click(function() { $("#theDiv").hide("normal"); }); $("#togglebtn").click(function() { $("#theDiv").toggle("slow"); });

24 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 });

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

Similar presentations

Ads by Google