Introduction to jQuery

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
this screencast will give you an introduction to jquery we'll explain what jquery is why you'd use it and then how you'd use it in your code after finishing this screencast you'll be able to use the core functionality of jquery in your projects and be on your way to writing unobtrusive javascript in powerful web applications to fully appreciate jquery let's quickly review some web development history back in the early days of the web people used tables and inline styling such as the font tag to build websites this made it difficult for search engines and screen readers to navigate the html markup more recently css evangelists started telling us we should have a separation between markup and layout this enables web developers and designers to build the same web page with separate styling and cleaner markup this has a number of benefits it improves the experience for screen readers and search engines but it also reduces load time with smaller html files and styling in only one file this also makes websites more manageable as broadband speeds became more common websites could become more complex using languages like javascript to deliver more desktop-like experiences on the web originally javascript would be included directly in the html markup this started cluttering the html a problem almost identical to the pre-css inline styling era the inclusion of inline javascript broke screen readers hindered readability by search engine spiders and often broken other browsers as before leaders of the web developer community advocated better ways of including javascript into web applications this separation of behavior from the html markup is called unobtrusive javascript just as the css evangelists told us there should be a separation of layout from markup javascript evangelists told us there should be a separation of behavior from markup let's say you want to open a pop-up in a new window when clicking a link there are several ways you can go about this one way would be to put a hash in the href attribute and move the javascript code into the onclick attribute here is the code working correctly in a browser with javascript enabled but as you can see if javascript is disabled the user is left stuck on the page a better way would be to include the pop-up file name in the href attribute as well as including the javascript in the on click attribute this way if the user disables javascript they can still access the pop-up but in the same window as the previous page however if we had several links like this we would be duplicating a lot of the same javascript code css enables us to describe our document's layout by assigning classes to elements we can use this technique to apply behavior to elements in an efficient manner the best practice would be to add a descriptive class such as new window to our link in order to apply our desired behavior to the link we need to implement the behavior in javascript first we need to apply the functionality when the document loads then we need to iterate through the document's anchors or links looking for our new window class the reason we're getting elements by tag name and then checking the class is because some older browsers such as ie6 don't have the method getelementsbyclassname so we have to cater to the lowest common denominator once we found the link in question we need to add the desired functionality return false tells the browser not to load the pop-up page in the current window when javascript is switched off the link will work as a standard link this is known as graceful degradation but this code is far from perfect there are a number of problems the window on load handler gets executed after the page and any images have loaded this means your application may not look as desired until the browser has finished loading the assets this code overrides any existing load or click handlers which could be in conflict with other behaviors this could be a problem if you're working on a project with two developers and you're both applying behavior to the same link if this were the case the last behavior executed would win the way we are checking for the classes applied to our links is very brittle it wouldn't work for links with more than one class applied to it for example our code wouldn't work for a link with a class attribute new window external link the way to overcome these issues is to use jquery jquery uses the same css selectors and syntax you're probably already using to style your pages so you almost already know how to apply behavior to your markup using jquery you don't have to worry about cross-browser compatibility since jquery selectors work in all modern browsers including ie6 it's also compatible with other javascript frameworks so you can use it alongside things such as dwr and prototype the behavior is ready faster than with traditional javascript since jquery provides an on ready handler which executes when the html file is downloaded but the images haven't yet the onload handler used by traditional javascript executes after the images have downloaded so jquery gets your behavior ready in milliseconds as opposed to seconds as you'll see jquery allows you to write less code and do more to use jquery in a project you first need to visit the jquery website as you can see there are two different versions one is 24 kilobytes for production and one is 155 kilobytes for development development is an uncompressed version of the jquery whereas the production has gone through a compression process known as minification minifying a javascript file means that all unnecessary white space newline characters and comments are removed the minification process can also pass the javascript file through an obfuscation process which reduces the amount of data transferred over the wire by shortening variables and function names when you download the production version of jquery you'll notice that the size of the file is not 24 kilobytes it's around 70 kilobytes this is not a mistake the jquery minified version is actually not 24 kilobytes but 70 kilobytes however if you go back to jquery.com the production version doesn't just say minified it also says gzipped g-zipping is a process for compressing plain text files such as html css and javascript between web server and web browser when a browser makes a request it sends a header to say that it accepts gzip compressed content the web server such as apache if configured correctly recognizes the request header and serves up the compressed file the browser in turn decompresses the requested file this conserves bandwidth and improves load times so if gzip compression is switched on the production jquery is 24 kilobytes over the wire most shared hosts have this set up already so you don't need to worry if you have your own self managed dedicated server you probably need to set it up yourself but this is beyond the scope of this screencast so if you need to do that look at the documentation for your web server however there is an alternative to serving up the jquery library yourself google has provided all major javascript libraries including jquery on their content distribution network with all the appropriate compression and caching switched on so you don't need to worry about this the other advantage of this is that many other sites use google's ajax libraries api to serve jquery what this means is that if a user has visited a site already using google's served up jquery it will be cached on their machine reducing load times on your site the only reason you wouldn't want to use this is if you're using jquery in an offline or sensitive environment such as an internal intranet site and you don't want to be going out on the web to include javascript once you've downloaded the version of jquery you want or found the url from google all you need to do is include the jquery file in your html somewhere this can be done in two places the first place is at the top of the page in the head tag this means you'll have to use the ready callback to execute jquery or javascript code first we are including google's hosted jquery the reason we have two script tags is because we are specifying a source for the first one which means that the contents of this tag would not get evaluated to get around this we include another tag and put our javascript in there when the html document has loaded and is ready to be manipulated by jquery the anonymous function or handler gets executed and the code is run you can remove document ready and it will still work either way is acceptable the second way of including jquery is at the bottom of the page just before the closing body tag but this time you don't need to use the ready event because the page is already downloaded and is ready to be manipulated so now it looks like this this way is recommended to increase page load speeds giving your users a better experience as you can see with both of our examples on how to include jquery the paragraph tag gets populated with the text hello jquery now let's move on to the main code example here is an example webpage with two forms and an article the code for this example is linked in the show notes in this example we're going to cover how to hide the forms when the page loads set up jquery functions to reveal the appropriate form when a link is pressed and show some basic validation on the form you'll learn how to select manipulate and transverse your html document using jquery so let's get to it open the index.html file in your browser as you can see we have two links sign in and sign up they link to their respective forms now open the index.html file in your editor of choice as you can see we have two links in an ordered list followed by two forums sign in and sign up and then an article the forms are very basic with a small number of fields if you'd like to familiarize yourself with the html feel free to pause the video at this point and review the code obviously showing the two forms on the page like this isn't desirable let's use jquery to hide the forms first we need to add jquery to our page then create an application.js file and then include that file in our document in order to identify the form containers in jquery we need to select them using css in this case we could use the div ids to identify each form container but in this example we're going to set up a class to group the containers together and apply the same behavior this allows us to add more forms in the future without modifying the javascript or jquery and still get the desired effect so let's add class equals forms to each of the form divs because we're including application.js at the end of the file we don't need to manually add the on ready callback all we need to do is put in the jquery behavior we want to be executed as soon as the file is loaded to hide the forms we simply add dollarsign.forms.hide to our application.js file as you can see when we refresh the page in our browser the forms are now hidden when we click on these links however nothing happens now we need to add the behavior to reveal the forms we need to add a click event listener to the link elements contained within the unordered list and list items in order to check that we are correctly binding this function to the link elements let's add a simple alert to verify in the function this refers to the dom element in which the click handler has been triggered in order to get the jquery representation of the dom element we need to enclose this in parentheses with the dollar sign in front of it now that we have a jquery representation of the object we can now use jquery methods on it the attr method can be used to access the value of a given attribute in this case href so let's check this out in the browser to see if it's working correctly okay great clicking on the link gives us the desired executed code if you notice the hash link is also exactly the same as the css selector for the relevant forms container so let's now select that using jquery and use the jquery show method in order to reveal it for the sake of convenience and readability we will create a local variable called id to show then we need to get the jquery representation of the element with that id by adding the jquery parentheses around id to show we then add dot show and as you can see it shows the correct form but if you notice when we click the other link it now shows both of the forms ideally we'd want the other forms container to hide in order to do this we create a local variable siblings and assign it to id to show dot siblings on the next line we write siblings.hide in order to hide the siblings if we launch this in the browser now we'll see that when we click on a button the entire page is hidden apart from our selected form this obviously isn't what we want so let's go back to our dot js file and be more specific in the siblings that we want to hide so within the siblings function we can pass in the css selector we want to hide in this case forms so our earlier decision to create the class forms to identify our form containers has now made this a trivial exercise if we had just used the ids of the containers we would have to implement a much more complex method to hide the form containers now that we've added the forms css selector to our siblings function we can see in our browser that the desired functionality of hiding the other form is working but the browser is jumping to the top of each form container when clicked to prevent this all we need to do is add return false to the end of our function which overrides the default browser behavior for a link jquery enables us to chain methods together so we can write this in fewer lines at the end of the show method we can add siblings.forms followed by dot hide what this is doing is getting the siblings of the container we want to show and hiding them now let's add a way to notify the user when the password fields don't match to do this we need to add a jquery event listener to our password confirmation field we need to watch for keystrokes on the field and compare it with the first password field the key up event is triggered after a key is pressed once again we need to implement an anonymous function to be triggered on key up on any type of input you can call val to retrieve the value of that particular input so here we need to see if the two passwords match or not if they don't match we'll add a css class called error to notify the user it could be named anything we're just using something sensible we need to remember to add some styling in our css to alert the user so now when we type test into our password field and test1 in our confirmation we see the error class being applied great but this isn't quite complete because when we correct the confirmation field the error class isn't removed to do this we just need to include an else statement to remove the error class when it matches simple here we can see that when the fields match the error class is being removed correctly finally we want to include a text message to notify the user when the passwords don't match first let's add an empty span tag right after our confirmation input in the html in order to get the span from the confirmation field we can transverse or move through the document by using the next method this will return the span element for you to manipulate all we need to do now is add the text method to the return span with the strings we want it to display so we'll display passwords don't match when they don't match and an empty string when they do match again we're chaining methods together but this could be written over many lines but chaining methods like this makes the code much easier to read hit refresh and we have our fully working example in this jquery introduction we've covered several main areas accessing attributes manipulating html transversing the document applying effects and handling events thank you for your time and we hope you'll have fun putting your new skills to use if you have any questions feedback or suggestions please email feedback at screencasts.org be sure to follow us on twitter and subscribe to our rss feed and newsletter to be notified about jquery and other web development screencasts as they become available see you next time you
Info
Channel: Screencasts dot org
Views: 6,994
Rating: undefined out of 5
Keywords: jquery, unobtrusive javascript
Id: HwMQzUDTby8
Channel Id: undefined
Length: 20min 23sec (1223 seconds)
Published: Mon Nov 21 2011
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.