Intro to jQuery jQuery is a popular, and extensible, JavaScript library Supports … DOM manipulation CSS manipulation HTML event methods Effects & animations AJAX Hosted by Google Microsoft For Google, include: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> For Microsoft, include: <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.2.min.js"></script>
jQuery Syntax $(selector).action() Selectors similar to CSS Element: $("p") ID: $("#mypicture") Class: $(".bigcaps") All: $("*") Current selected element: $(this) Additional selectors :first, :last, :even, *odd :eq, :gt, :lt, :not [attribute], [attribute=value] See http://www.w3schools.com/jquery/jquery_ref_selectors.asp for a list of selectors
jQuery Event Methods Wait for document to load first: $(document).ready(function(){ // jQuery methods go here… }); Respond to a mouse click: $("p").click(function(){ // what to do when paragraph clicked… }); Respond to mouse hovering: $("#myimg1").hover(function(){ // what to do on mouseenter… }, function(){ // what to do on mouseleave… }); See http://www.w3schools.com/jquery/jquery_ref_events.asp for jQuery events handled
Other jQuery Methods css() each() Return a value $(selector).css("propertyname") Change a value $(selector).css("propertyname", "value") each() Used to iterate through matched elements $(selector).each(function() { // code for manipulating each }); See http://www.w3schools.com/jquery/ for more
jQuery Data Including data in an element <element data-name=value> Retrieving data $(element).data(name) Storing data $(element).data(name, value) See http://www.w3schools.com/jquery/ for more
Parallax Scrolling Create a webpage with elements to be scrolled Identify regular & slower scrolling elements Use data attributes to represent speed & initial position of slower elements Set CSS styles Elements scrolling normally get position:absolute; Elements scrolling more slowly get position:fixed;
Parallax Scrolling (con't) Use jQuery to initialize element positions $('img').each(function() { var ptop = eval($(this).data("top")); var pleft = eval($(this).data("left")); $(this).css('top', ptop + 'px'); $(this).css('left', pleft + 'px'); }); Define parallax function function parallax(){ var scrolled = $(window).scrollTop(); $('img').each(function() { var speed = eval($(this).data("speed")); var ptop = eval($(this).data("top")); $(this).css('top', ptop - (scrolled * speed) + 'px'); }); } Call function when the window scrolls $(window).scroll(function(e){ parallax(); });