130 likes | 282 Views
jQuery - Using selectors. Learning Objectives. By the end of this lecture, you should be able to: Select items using jQuery based on ID, class name, or HTML tag. Apply some simple functions such as fadeIn(), fadeOut(), hide(), and show() to content that you have selected.
E N D
Learning Objectives By the end of this lecture, you should be able to: • Select items using jQuery based on ID, class name, or HTML tag. • Apply some simple functions such as fadeIn(), fadeOut(), hide(), and show() to content that you have selected. • Demonstrate a very basic understanding of what the document object model (DOM) is. • Invoke the getElementsByTagName() and getElementById() JavaScript functions.
Why we use JS Scripting is easily the most powerful way we can turn a static web page into something much more dynamic and reactive. Some of the things we do with scripts include: • Form validation: For example, if the user forgets to enter their phone number in a form, you can make sure that the page is not submitted until they do so. You might also confirm that their phone number does not contain any characters other than digits, parentheses, or dashes. • Hiding/Showing things: For example, a common feature is to have items appear or disappear in response to a mouseover. In image shown here, a bubble appears when I mouse-over the ‘Breakfast at Tiffany’s’ title on Netflix. • Animation/Positioning: You can animate and/or reposition elements on a web page as needed – even after the page has loaded. • Appearance: You can cause sections to change their appearance based on timing, user behavior, form entry, and much more.
The basic process The basic process to manipulate content on a web page is to first select the content and then do something with the content you have selected. • Select an element or section: You can select all elements of a specific selector (e.g. all ‘h2’ tags), or you can fine-tune your selections. Here are some examples of elements/sections that you can select: • All ‘h2’ tags • All ‘h2’ tags that are colored green • All ‘a’ tags • All ‘a’ tags linked to google.com • A div section that has an id of ‘footer’ • Do something with the item you selected: Once you have made your selection, you can do all kinds of things with that selection. For example, suppose you selected a div section with an id of ‘quotation’. Things you might do with this selection could include: • Change the width of that section • Change its background color • Cause the selection to “dance” across the screen • Temporarily hide the section and only have it appear when the user moves the mouse over a certain image. • Cause an audio clip of the quotation to play in response to the user clicking on a certain icon. • Retrieve all of the text inside the quotation and convert it all to upper-case text.
Selecting content using JavaScript(as opposed to jQuery) Remember that jQuery, is essentially a ‘dialect’ of Javascript that provides us with all kinds of shortcuts for code that would take many, many lines of JS. Therefore, though we will be using jQuery the vast majority of the time, I will begin with a (very) brief overview on how to select items using JS. In particular, we will learn two JS functions for selecting content. After we have learned these two functions, we will focus on selecting content using jQuery. Selecting items using JS: • Underlying every web page is something called the ‘Document Object Model’, or ‘DOM’. The DOM is part of the W3C’s standard for organizing the underlying structure of a web page. One of the main purposes of the DOM is to allow developers a way of accessing items on an HTML page using JS. Items in the DOM can be accessed in a variety of ways, one of which uses something called ‘array’ notation. For example, you can use JS to retrieve the third ‘p’ tag on the page and then find out the name of the first ‘descendant’ tag of that ‘p’ and change it’s appearance. (If that is confusing to you – don’t worry – it’s most definitely not something you’ll have to do. For now…) • A much easier (though still sometimes problematic) way of retrieving content in JS is via the functions getElementsByTagName() and the closely related getElementById() . • These two functions are the only Javascript tools that we will learn for selecting content. After that, we will focus mostly on selecting content using jQuery. However, do be sure you know how to do basic selecting using these functions.
The getElementById() and getElementsByTagName() functions Easiest way to demonstrate this is via an example: var temp = document.getElementsByTagName('p'); //temp now stores a link to all ‘p’ tags //on your page. If you know the JS command to, say, //change the color of ‘temp’, the content inside //all the ‘p’ tags would change color. document.getElementById('random_text').innerHTML="Hello!!"; //Will take whichever tag has an ID of ‘random_text’ and //replace whatever HTML content is inside that tag with //the text Hello!! That’s all we are going to say about these functions for now. We may periodically return to them at some points throughout the course.
A (very) quick look at the DOM Working with the DOM requires understanding that all tags are either ancestors or descendants to other tags. In the example here, the <strong> tag is a child of the <p> tag which is a child of the <body> tag which is a child of the <html> tag. The <html> tag is the ancestor (the ‘Adam’ if you will) of ALL tags on the page. The good news? That’s all you need to understand about the DOM for now!!
Limitations of the DOM • While the DOM’s primary purpose is standardization, in reality, different browsers frequently interpret the DOM differently. As a result, JS programmers have (in the past) had to write lots and lots of code to deal with the various different browsers. Once again, libraries such as jQuery come to the rescue. There is a tremendous amount of code written by jQuery developers that handles many of the messy details for us. • One important axiom of programming is: “Don’t reinvent the wheel.” In other words, if someone else has already written tried-and-true code to accomplish a certain task, then, use it!! • That being said, it is, of course, always important to learn the fundamentals of what is going on ‘under the hood’. Understanding the underlying theory is vital as it is the main tool that you have for debugging problematic web pages.
Selecting items the jQuery way jQuery also allows us to easily select items, however, it does so with some additional – and very important – control that is either unavailable or difficult to accomplish by using the getElementById() or getElementsByTagName() functions. Here is an overview of how we select items in jQuery: $('tag_or_selector_name') E.g. $('h2') $('#id_name') E.g. $('#citations') $('.className'); E.g. $('.emphasize') • Note that jQuery commands begin with a $ sign. • To select based on a selector (i.e. a tag name), simply name the selector. • To select based on an ID (known as a contextual selector), you must precede the ID with a pound sign, ‘#’. • To select based on a CSS class name, you must precede the identifier with a period ‘.’ • All of these are placed inside quotes (we nearly always use single quotes)
“Doing” something with selected items • Now that we have learned the very basic method selecting items using jQuery, let’s talk about doing something with selected items. • There are many, many, jQuery functions that can be applied to a selected item. Obviously, which functions are available to a selected element depends on the particular element. For example, you can change the color of a ‘p’ tag, but not the color of a ‘meta’ tag. $('#random_text').fadeOut(2000); $('#random_text').fadeIn(2000); $('.emphasize').hide(); • As you may have worked out, these lines of code will cause any content contained within an ID called ‘random_text’ to first fade out (over a period of 2000 milliseconds) and then to fade in, also over 2 seconds. • The third line says to take every tag to which the class called ‘emphasize’ has been applied, and to make it invisible. • FILE: jquery_select_modify.htm
Common Pitfalls • When you are first learning this material, the following mistakes are easy to make. Keep an eye out for them as it can save you significant debugging time! • Forgetting to place the ‘#’ before the identifier when you are trying to select based on an ID. • Forgetting to place the ‘.’ before the identifier when you are trying to select based on a class name. • Forgetting that when you select, you are selecting ALL items that match. For example, $(‘.emphasize’) will select ALL items to which the emphasize class has been applied.
Recap • In this discussion we focused on selecting items based on the selector (tag), IDs (contextual selectors), and CSS classes. • We then learned how to apply a couple of very simple jQuery functions to those selected items. • We intentionally kept the functions very simple. In our upcoming discussions, we will, of course, learn how to apply more advanced and subtle selections and apply increasingly interesting/fun/advanced functions.