Chapter 11 JQuery Objectives What j Query is
Chapter 11 JQuery
Objectives • What j. Query is • What Nu. Get is and how to use it • How to use j. Query to enhance your pages, including adding rich visual effects and animations • How to leverage j. Query to enhance the ASP. NET validation framework
Why Jquery? • Javascript is the default language used in web browsers, however subtle differences in javascript code cause it to be interpreted differently in differently browsers. • Core Javascript lacks some useful functionality that we need to work with the elements (for example, finding an element by CSS Class name). • Libraries have been created to extend Javascript to be more powerful • • Prototype (http: //prototypejs. org) • Scriptaculous, an add-on to Prototype (http: //script. aculo. us) • Ext JS (www. sencha. com/products/extjs/) • Dojo (http: //dojotoolkit. org) • Moo. Tools (http: //mootools. net/) Jquery has proved to be one of the most popular and widely supported.
JQuery • The main focus of the j. Query library has always been to simplify the way you access the elements in your web pages, provide help in working with client-side events, enable visual effects like animations, and make it easier to use Ajax in your applications. • You can download the latest at http: //jquery. com and find great documentation there. • You can use ASP. NET Web Forms Site template to create a new site, because it already contains a Scripts folder with the necessary j. Query files. • You can add Jquery through a CDN (Content Delivery Network) or by using a package manager known as Nuget.
Using Nu. Get Package Manager • Nu. Get is an open source Library Package Manager that comes as a Visual Studio extension and that makes it very easy to add, remove, and update external libraries in your Visual Studio projects and websites. • Initially developed by Microsoft but has now been turned into an Open Source project that accepts contributions from the developer community. • To manage libraries with Nu. Get, you have two options: • you can use the Manage Nu. Get Packages • dialog box or you can use the Package Manager Console.
Manage Nu. Get Packages • You access this dialog box by right-clicking your website in the Solution Explorer and choosing Manage Nu. Get Packages. Alternatively, choose Tools ➪ Library Package Manager ➪ Manage Nu. Get Packages for Solution
Using Nu. Get • Manage Nu. Get Packages: • On the left menu, you can see the Installed, Online or Updates to packages. • Using the Online portion, you can check for online packages by name and choose “Install”. Nu. Get will automatically install the packages and set up your Visual Studio project to reference those libraries. • The other way to get packages is to use the Package Manage Console, a command line prompt to install the packages. • Use “Get-Help Nu. Get” to get a list of commands
Using Nu. Get • Probably the most popular commands are Get-Package and Install-Package. • Using Get-Package you can list the packages that are currently installed in your site. You can –List. Available and –Filter Get-Package -List. Available -Filter j. Query • Once you find the package you want to install, use the Install-Package command. As an argument, you need to supply it the name of the package. • For example, to install j. Query into your website you execute the following command: Install-Package j. Query
Jquery Package • The 4 Jquery libraries added are the following: • Jquery intellisense: used for intelissense pop-ups • Jquery: core j. Query code, uncompressed • Jquery. min: core j. Query code, compressed • Jquery. min. map: allows for debudding, provides mapping Between compressed and uncompressed • For deployment to production, always use compressed file
Including JQuery • To include j. Query in your website, you have a couple of options: • Add a reference to the j. Query library in just the web pages or user controls that require it. • Add a reference to the j. Query library in the master page of your site so it’s available in all pages. • Note that once they’ve visited a page that does reference the library, the browser will cache a copy of it, removing the need to download it again on subsequent visits to pages. • You can embed a reference to the library in a page, user control, or master page using the standard <script> syntax: <script src="/Scripts/jquery-2. 0. 3. min. js" type="text/javascript"></script>
Including JQuery • You can use the Script. Manager control <asp: Script. Manager ID="Script. Manager 1" runat="server"> <Scripts> <asp: Script. Reference Path="~/Scripts/jquery-2. 0. 3. min. js" /> </Scripts> </asp: Script. Manager> • Another alternative is to refer to an online version of the library with Microsoft’s Content Delivery Network (CDN) or Google Code. • For more information on this, visit Microsoft’s CDN site at www. asp. net/ajax/cdn or Google’s API site at http: //code. google. com/apis/ajaxlibs/. • The advantages of using online versions of external libraries are improved performance and lowered bandwidth for your servers. • Because it is likely that visitors to your site already have downloaded the shared scripts when visiting another site, they don’t have to download them again when visiting yours.
Jquery Syntax • It’s important to wait with executing your code until the page is done loading the DOM. • The DOM — the document object model — is a hierarchical representation of your web page and contains a treelike structure of all your HTML elements, script files, CSS, images, and so on. • The DOM is always in sync with the page you see in the browser, so if you make a programmatic change to the DOM (for example, with j. Query code), the change is reflected in the page in the browser. • If you execute your j. Query code too early (for example, at the very top of the page), the DOM may not have loaded the elements you’re referring to in your script, and you may get errors.
Ready function • Jquery provides the ready function $(document). ready(function() { // Code added here is executed when the DOM is ready. }); • Any code added here is executed once the page is ready for DOM manipulation. • The ready function has a shortcut to call it like so: $(function() { // Code added here is executed when the DOM is ready. });
Selecting Items Using JQuery • In j. Query you use the dollar sign ($) as a shortcut to find elements in your page. • The elements that are found and returned are referred to as a matched set. The basic syntax for the $ method is this: $('Selector Here') • The $ method returns zero or more elements that you can then influence using one of the many j. Query methods • For example, to apply some CSS to all h 2 elements, you use the css method: $('h 2'). css('padding-bottom', '10 px');
Chaining / Fluent Programming • Besides applying some design or behavior, Jquery returns the matched set again. • This enables you to call another method on the same matched set so both are applied. • This concept is called chaining or fluent programming where you use the result of one method as the input of another, enabling you to create a chain of effects. • For example, the following code first changes the font size of all level-two headings in the page, and then fades them out until they are invisible in five seconds: $('h 2'). css('font-size', '40 px'). fade. Out(5000); // timeout is in milliseconds
Basic Selectors • Jquery Selectors allow you to find elements in the DOM and use the same properties that we learned in CSS selectors. • Universal Selector: Matches all elements. $('*'). css('font-family', 'Arial'); • Element Selector: Matches a particular element. $('h 2'). css('color', 'blue'); • ID Selector: Matches the HTML Id. $('#Button 1'). add. Class('New. Class. Name'); • Class Selector: Matches the specific class. $('. Highlight'). css('background-color', 'red');
Group and Combine Selectors • You can Group Selectors. The following affects all h 1 and h 2 elements on the page $('h 1, h 2'). css('color', 'orange'); • You can combine elements in to find elements that fall under others. The following finds all the paragraph with the Main. Content element $('#Main. Content p'). css('border', '1 px solid red');
Examples of Selectors $('*'). css('color', 'Green'); // Universal • What it does: Changes the font of all elements to green $('#Sidebar'). css('border-bottom', '2 px solid red'); // ID • Finds an element by ID and changes its bottom border to red $('h 1'). bind('click', function () { alert('Hello World') }); // Element • Finds the H 1 element and dynamically binds the function specified to the click button $('. Sample. Class'). add. Class('Please. Wait'). hide(5000); // Class • Finds the element by class and applies a new class then hides it for 5 seconds
Examples of Selectors $('footer, header'). slide. Up('slow'). slide. Down('slow'); // Grouped • Find both the footer and the header elements. The slide. Up method then slowly decreases the height of these elements until they have completely disappeared. In doing so, it remembers the initial size, so when you call slide. Down again it knows to what size to restore the elements. $('#Sidebar img'). fade. To(5000, 0. 1); // Combined • Combined selector to find the banner image in the right-hand sidebar. Once it has found the image, it slowly dissolves it (in five seconds) by setting its opacity to 0. 1 (10%) so it gets almost invisible.
Basic Filters • In j. Query you can use filters to further filter the result set from a selector. • Order of operation, Selector gets applied first, then the filter.
Basic Filters • For a complete list, go to http: //api. jquery. com/category/selectors/
Advanced Filters • j. Query supports a lot more filters that enable you to get items based on the text they contain, whether or not they are visible, and also on any attributes they may have.
Advanced Filters
Advanced Filters
Modifying the DOM with JQuery • Jquery provides ways to modify the DOM elements. • CSS Methods: • Css(name, value): Sets the css value $('h 1'). css('background-color', 'green'); • Css(name): Retrieves the css value for the property specified alert($('h 2 span'). css('font-style')); • Css(properties): Sets multiple properties at once $('#Demo. Table td'). css({'color' : 'red', 'font-family' : 'Verdana', 'padding' : '10 px'}); • add. Class, remove. Class, and toggle. Class: Adds a class, removes a class, or toggles (adds if not there or removes if there). $('h 2'). add. Class('Please. Wait'); $('h 2'). remove. Class('Please. Wait');
Modifying the DOM with JQuery • attr(attribute. Name): Retrieves an existing attribute value alert($('h 1'). attr('title')); • attr(attribute. Name, value): Sets an attribute to a new value $(': checkbox'). attr('checked', true);
Handling Events with JQuery • Many HTML elements have events, such as the click, mouseover, mouseout, etc… <input type="button" onclick="Say. Your. Name(); " value="Click Me" /> • Jquery allows you to hook up events to multiple elements and the bind method assigns a function to an event. • The this keyword in this example refers to the element to which the item is applied: $(function() { $('#Demo. Table tr'). bind('mouseover', function() { $(this). css('background-color', 'yellow') }); $('#Demo. Table tr'). bind('mouseover', function() { $(this). css('background-color', 'yellow') }). bind('mouseout', function() { $(this). css('background-color', '') });
Effects with JQuery
Effects with JQuery
Effects with JQuery
Other Useful Jquery methods • . each : iterates or loops over a collection $('#Demo. Table td'). each(function() { alert(this. inner. HTML); }); • . prev: traverses to the previous element in the case of sibling elements alert($('#Demo. Table td: contains("Row 1 Cell 2") '). prev()[0]. inner. HTML); • . parent: traverses to the parent element in the DOM structure alert($('#Demo. Table td: contains("Row 1 Cell 2") '). parent()[0]. inner. HTML);
Jquery and Validation • Rather than embedding large chunks of Java. Script code in the page, ASP. NET developers have written a small Java. Script library that uses j. Query under the hood to perform the validation. • This, known as unobstrusive javascript, separates the executed validation code from the structure and content of the page. • This leads to cleaner code and reduces the size of the page. • Configuring the validation framework to use unobtrusive validation with j. Query instead of the built-in code that is generated is a three-step activity: 1. Enable unobtrusive validation in the Web. config file. 2. Register the j. Query library with the Script. Manager in the Global. asax file. 3. Install a package that contains Java. Script files to handle the client side validation.
Jquery and Validation • In the Global. asax, add the following code to the Application_Start method void Application_Start(object sender, Event. Args e) { Route. Config. Register. Routes(System. Web. Routing. Route. Table. Routes); Script. Manager. Script. Resource. Mapping. Add. Definition("jquery", new Script. Resource. Definition { Path = "~/Scripts/jquery-2. 0. 3. min. js" } ); }
Jquery and Validation • Add the following to the web. config • In order to use unobtrusive validation together with j. Query, you need to install the package Microsoft. Asp. Net. Script. Manager. Web. Forms. To do this, open the Package Manager Console, enter the following command hit enter: <app. Settings>. . . <add key="Validation. Settings: Unobtrusive. Validation. Mode" value="Web. Forms" /> </app. Settings> Install-Package Microsoft. Asp. Net. Script. Manager. Web. Forms
Jquery and Validation • On a master page or aspx page, add the following <asp: Script. Manager ID="Script. Manager 1" runat="server"> <Scripts> <asp: Script. Reference Name="jquery" /> <asp: Script. Reference Path="~/Scripts/Web. Forms/Web. UIValidation. js" /> </Scripts> </asp: Script. Manager> • Validation now uses the j. Query library and the data-attributes added to the HTML elements.
Try it Out • Pg. 374 • Pg. 377 • Pg. 383 • Pg. 385 • Pg. 399
Summary • In this chapter we covered: • Learned what j. Query is • Learned What Nu. Get is and how to use it • Understood ow to use j. Query to enhance your pages, including adding rich visual effects and animations • Understood how to leverage j. Query to enhance the ASP. NET validation framework
- Slides: 37