320 likes | 453 Vues
Dive into the world of jQuery, a powerful JavaScript library that simplifies HTML document traversing, event handling, animating, and Ajax interactions. This session is designed for developers with a basic understanding of JavaScript, HTML, and CSS. Learn how to effectively reference jQuery, utilize CDN for optimized performance, and apply various jQuery selectors to interact with the DOM. Discover how to handle events seamlessly across different browsers and manipulate styles with ease. Join us to enhance your web development skills with practical examples and hands-on coding exercises.
E N D
Pre- Reqs • Experience working with Javascript • Good Understanding of HTML • Experience working with css
Agenda • Getting start with Jquery • Why use jQuery & How referencing Jquery • Using CDN with a Fallback • Using the jQuery Selectors • Intracting with the DOM • Handling Events • Working with Ajax Features
Getting Start with jQuery • What is Jquery? • Javascript Library(single file) • Cross-browser support • Select HTML element • Handle events • Animate HTML element • Make Ajax Call • 1000’s of plugins available
Why use JQuery • How do you locate element with specific class?? • How do you apply styles to multiple elments? • How do you handle events in cross-browser manner? • How many hours have you spend dealing with cross-browser issue??
Referencing a Jquery script • Go to jquery.com • Choose ur compression level • Download
Content Delivery Network(CDN) • Content Delivery Network(CDNs) Provide Several benfits: • Catching of Scripts • Support for http and https • Regional server – decreased latency • Allows for more concurrent call(parallelism)
Using a content Delivery Network(CDN) • CDN Providers : Google,Microsoft,jQuery and others provide CDNs that host script such as jQuery: <script src=“//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js"> </script> OR <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> You can get google CND from https://developers.google.com/speed/libraries/devguide No protocol define
What if CDN is Down • If there was a problem with the CDN u can load the script locally <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script> window.jQuery || document.write('<script src="js/libs/jquery-1.7.1.min.js"><\/script>') </script>
Using the jQuery Ready Funciton • Use $(document).ready() to detect when a page has loaded and is ready to use • Call once DOM hierarchy is loaded (but before all image have loaded) <script type=“text/javascript”> $(document).ready(function(){ //Performaction here }) </script>
CSS Selectors vsjQuerySelctors CSS Selectors element {} #id {} class {} selector1, selector2 {} ancestor descendant {} parent > child {} :nth-child() {} jQuery Selectors $('element') $('#id') $('.class') $('selector1, selector2') $('ancestor descendant') $('parent > child') $(':nth-child(n)')
Using jQuery Selectors • What is Selectors • Selectors allow page element to be selected • Single or multiple element are supported • A selector identifis an HTML element/tag that u will manipulate with JQuery code <div id=“EmpDiv” class=“higlight”> < span class=“Text”>John < /span></div> $(‘div’).text(‘ABC’) or jQuery(‘div’).text(“ABC”) $(‘.Text’).text(‘xz’) or jQuery(‘.Text’).text(‘xz’)
Intracting with the DOM • Iterating Through Nodes • Modifying DOM Object Properties • Modifying Attributes • Adding and Removing Nodes • Modifying Styles • Modifying Class
Iterating Through Nodes • each(function(inedex,element){}) is used to iterating through jQuery Object: $('span').each(function(index){ alert((index+1)+" -- "+$(this).text()); }); • Iterating through each div element and returns its index number and text $('span').each(function(index,elem){ alert((index+1)+" -- "+$(elem).text()); });
Modifying Object Properties • The this.propertyName statement can be used modify an object’s property directly $(this).each(function(){ this.title=“Some title” }); Or Get Attribute Var x=$(“.DivClass”).attr(‘title’) Set Attribute $(“.DivClass”).attr(‘title’,’Sometilte’)
Modifying Multiple Attributes • To modify multiple attributes, pass JSON object containing name/value pair $(‘img’).attr({ style:”border:2px solid black”, title:”My Image Title” }); Json object passed and used to change title and border
Adding and Removing Nodes • Four key method handle inserting nodes into elements; • .append() • .appendTo() • .prepend() • .prependTo() • To remove node from element use .remove() • $(element).remove()
Wrapping Element • The following HTML and .wrap() function: • <div class=“state”>Kerala</div> • $(‘.state’).wrap(‘<div class=“India”/>’); • Result: <div class=“India”> <div class=“state”>Kerala</div> </div>
Modifying Style • The .css() function can be used to modifying an Object’s style: $(“div”).css(“color”,”red”) • Multiple style can be modified by passing a JSON object: $(“div”).css({ ‘color’:’red’,’font-size’:’13pt’ })
Modifying CSS Classes • The four method for working with CSS Class attributes are: • .addClass() • .hasClass() • removeClass(); • toogleClass();
Handling Events • Click() • Blur() • Focus() • Dblclick() • Mousedown() • Mouseup() • Keydown() • Keypress() • See more att http://api.jquery.com/category/events
Handling Click Events • .click(handler(eventObject)) is used to listen for a click event or trigger a click event on an element $(‘#myID’).click(function(){ alert(“The element myID was clicked”) }) .Trigger $(‘#myID’).trigger(‘click’) or $(‘#myID’).click()
Use bind • .bind(evnetType,handler(eventObject)) attaches a handler to an event for the selected elements • $(‘#myDiv’).bind(‘click’,function(){ • //handle click event • }) • .click() is same as .bind(‘click’)
Binding Multiple Event • Bind() allow multiple events to bound to one or more element • Event names to are separated with a space: • $(‘#myDiv’).bind(‘mouseentermouseleave’,function(){ • $(this).toggleClass(‘enterd’); • })
Using Unbind() • .unbind(event) is used to remove a handler previously bound to an element: • $(‘#test’).click(handler); can be unbound using • $(‘#test’).unbind() • Specific events can also be targeted using unbind() • $(‘#test’).unbind(‘click’)
live() and delegate() function • live() and delegate() allow new element added into DOM to automatically be “attached” to an event handler • live() – allows binding of event handler to elements that match a selector, including future element. • delegate() replace for live() in jQuery 1.4 Attaches event handler directly to the selector context.
Working with Ajax Features • Loading HTML content form Server • $(selector).load(url,data,callback) allow HTML content to be loaded from a server and added into a DOM object • $(document).ready(function(){ • $(‘#hlbbutton’).click(function(){ • $(‘#Mydiv’).load(‘helpDtl.html #mainTOc’); • }) • })
Example • Many apps scatter Ajax calls throughout the code $('#customerButton').click(function(){ $.getJSON("/getData",function(data){ varcust= data[0]; $('#ID').text(cust.ID) $('#FirstName').text(cust.FirstName) $('#LastName').text(cust.LastName) })});
Example • When submitting a form use .serialize() $('#myform').submit(function(event){ event.preventDefault(); varformUrl=$(this).attr('action'), formData=$(this).serialize()‘ $.ajax({ url: formUrl, data: formData }); })
Ajax Resoponses • Before jQuery 1.5, these were handled by tree more option() • {success:function(){},error:function(){},complete:function(){}} • $.ajax({ • url:'/url/to/serverResource', • success: function(response,status,xhr){ • //do something after successful request • }, • error:function(xhr,status,erroThrown){ • //handle failed request • } • complete: function(xhr,status) • { • //do something whether sucess or error • }}