Website Development Lecture 18: Working with JQuery ================================================================================== JQuery

Similar documents
Why Use A JavaScript Library?

Introduction to WEB PROGRAMMING

WELCOME TO JQUERY PROGRAMMING LANGUAGE ONLINE TUTORIAL

Week 8 Google Maps. This week you ll learn how to embed a Google Map into a web page and add custom markers with custom labels.

Using Dreamweaver CC. Logo. 4 Creating a Template. Page Heading. Page content in this area. About Us Gallery Ordering Contact Us Links

jquery Tutorial for Beginners: Nothing But the Goods

CS7026. Introduction to jquery

Chapter 9 Introducing JQuery

Microsoft Expression Web Quickstart Guide

Getting started with jquery MIS Konstantin Bauman. Department of MIS Fox School of Business Temple University

Section 1. How to use Brackets to develop JavaScript applications

BEFORE CLASS. If you haven t already installed the Firebug extension for Firefox, download it now from

Guidelines for doing the short exercises

ITS331 Information Technology I Laboratory

Welcome Please sit on alternating rows. powered by lucid & no.dots.nl/student

SEEM4570 System Design and Implementation Lecture 04 jquery

CSC 337. jquery Rick Mercer

Using Dreamweaver CS6

How to lay out a web page with CSS

5 Snowdonia. 94 Web Applications with C#.ASP

Frontend guide. Everything you need to know about HTML, CSS, JavaScript and DOM. Dejan V Čančarević

2. Write style rules for how you d like certain elements to look.

How to create and edit a CSS rule

Introduction to Multimedia. MMP100 Spring 2016 thiserichagan.com/mmp100

Client Side JavaScript and AJAX

JQuery. UNIVERSITY OF MASSACHUSETTS AMHERST CMPSCI 120 Fall 2010

CodeValue. C ollege. Prerequisites: Basic knowledge of web development and especially JavaScript.

Using Development Tools to Examine Webpages

729G26 Interaction Programming. Lecture 4

Class 3 Page 1. Using DW tools to learn CSS. Intro to Web Design using Dreamweaver (VBUS 010) Instructor: Robert Lee

Study Guide 2 - HTML and CSS - Chap. 6,8,10,11,12 Name - Alexia Bernardo

This document provides a concise, introductory lesson in HTML formatting.

Dreamweaver MX The Basics

Animation and style sheets

Before you begin, make sure you have the images for these exercises saved in the location where you intend to create the Nuklear Family Website.

Fish Eye Menu DMXzone.com Fish Eye Menu Manual

CSC309 Winter Lecture 2. Larry Zhang

JavaScript: Events, the DOM Tree, jquery and Timing

CSS worksheet. JMC 105 Drake University

JQuery WHY DIDN T WE LEARN THIS EARLIER??!

Data Visualization (CIS 468)

Dynamism and Detection

Unveiling the Basics of CSS and how it relates to the DataFlex Web Framework

Bonus Lesson: Working with Code

E , Fall 2007 More with stylesheets

SEEM4570 System Design and Implementation. Lecture 3 Events

Dreamweaver Tutorial #2

State of jquery Fall John Resig

Make a Website. A complex guide to building a website through continuing the fundamentals of HTML & CSS. Created by Michael Parekh 1

SASS Variables and Mixins Written by Margaret Rodgers. Variables. Contents. From Web Team. 1 Variables

Multimedia im Netz Online Multimedia Winter semester 2015/16

**Method 3** By attaching a style sheet to your web page, and then placing all your styles in that new style sheet.

Want to add cool effects like rollovers and pop-up windows?

ADDING CSS TO YOUR HTML DOCUMENT. A FEW CSS VALUES (colour, size and the box model)

COURSE OUTLINE MOC 20480: PROGRAMMING IN HTML5 WITH JAVASCRIPT AND CSS3

SEEM4570 System Design and Implementation. Lecture 3 Cordova and jquery

Wanted! Introduction. Step 1: Styling your poster. Activity Checklist. In this project, you ll learn how to make your own poster.

Siteforce Pilot: Best Practices

Stephen Walther Senior Program Manager Microsoft Corporation

HTML and CSS a further introduction

Quick Start Guide. This guide will help you get started with Kentico CMS for ASP.NET. It answers these questions:

Techniques for Optimizing Reusable Content in LibGuides

Locate it inside of your Class/DreamWeaver folders and open it up.

Introduction to HTML & CSS. Instructor: Beck Johnson Week 5

Using Dreamweaver. 6 Styles in Websites. 1. Linked or Imported Stylesheets. 2. Embedded Styles. 3. Inline Styles

RICH ENTERPRISES. Small Business Series. Getting Started with HTML

Which is why we ll now be learning how to write in CSS (or cascading sheet style)

FolderView DMXzone.com Folder View 2 Manual

The default style for an unordered (bulleted) list is the bullet, or dot. You can change the style to either a square or a circle as follows:

20486-Developing ASP.NET MVC 4 Web Applications

Practical 5: Reading XML data into a scientific application

Using AJAX to Easily Integrate Rich Media Elements

Dreamweaver CS5 Lab 4: Sprys

Dear Candidate, Thank you, Adobe Education

Internet: An international network of connected computers. The purpose of connecting computers together, of course, is to share information.

Your First Windows Form

The head Web designer walks into your sumptuous office and says, We

Introducing Databases

Code Editor. The Code Editor is made up of the following areas: Toolbar. Editable Area Output Panel Status Bar Outline. Toolbar

Interactive Tourist Map

Getting Started with Eric Meyer's CSS Sculptor 1.0

ThingLink User Guide. Andy Chen Eric Ouyang Giovanni Tenorio Ashton Yon

Designing for diverse devices. Dr. Andres Baravalle

ITSE 1401 Web Design Tools Lab Project 4 (Expression Web 4 - Units M, N, O, P) Last revised: 1/9/14

COMS 359: Interactive Media

HTML CSS JAVASCRIPT WEB PUBLISHING IN ONE HOUR A DAY SAMS TEACH YOURSELF COVERING HTML5 CSS3 AND JQUERY 7TH EDITION

Block & Inline Elements

Websites WHAT YOU WILL LEARN IN THIS CHAPTER: WROX.COM CODE DOWNLOADS FOR THIS CHAPTER

We aren t getting enough orders on our Web site, storms the CEO.

Designing the Home Page and Creating Additional Pages

Welcome to the wonderful world of Dreamweaver 8. If you re an experienced

Introduction to AngularJS

Quick.JS Documentation

HTML/CSS Lesson Plans

RAGE WebDesign Quick Start 1 of 18. Welcome To RAGE WebDesign

Moving from FrameMaker to Blaze: Best Practices

HTML and CSS: An Introduction

UI Course HTML: (Html, CSS, JavaScript, JQuery, Bootstrap, AngularJS) Introduction. The World Wide Web (WWW) and history of HTML

HTML 5 and CSS 3, Illustrated Complete. Unit L: Programming Web Pages with JavaScript

Using Dreamweaver CS6

Transcription:

JQuery What You Will Learn in This Lecture: What jquery is? How to use jquery to enhance your pages, including adding rich? Visual effects and animations. JavaScript is the de facto language for client-side scripting and interacting with elements in your web pages at the client. JavaScript can do much more and is quite a powerful programming language. But powerful as it may be, it has a few shortcomings. One of the problems with JavaScript is that not all browsers interpret it the same way. A lot of the JavaScript code you ll write will work in all major browsers, but subtle differences in code and behavior exist that make it difficult to write code that behaves exactly the same in all major browsers. Also, JavaScript lacks some useful features that would come in handy in your day-today JavaScript coding. For example, it has built-in methods to find a specific element on a page (using getelementbyid) and to find all elements of a specific HTML tag (using getelementsbytagname), but it lacks features like getelementsbyclassname to get a list of elements with a specific class applied to them. The client-side ASP.NET AJAX Library you were introduced to in the previous lecture helps to overcome some of these problems, but it isn t enough in all situations. Fortunately, the Internet developer community has been very active developing frameworks that use JavaScript under the hood and that extend its power, while offering a very rich feature set that helps you create interactive client-side web pages. Over the years, many JavaScript libraries have been developed most of which are free including: Prototype (http://prototypejs.org) Scriptaculous, an add-on to Prototype (http://script.aculo.us) Ext JS (http://extjs.com) Dojo (http://dojotoolkit.org) One of the frameworks that have gotten a lot of attention is jquery. Initially developed and released by John Resig in January 2006, jquery has grown to be a very 1

popular client-side framework. It also caught the attention of Microsoft, which decided to start shipping jquery with Microsoft products. Initially, jquery shipped with the Microsoft ASP.NET MVC Framework, but it s now also included in Visual Studio and Visual Web Developer 2010. An Introduction to jquery The main focus of the jquery 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. In January 2006, John Resig announced the first version of jquery, which was followed by an official release of jquery 1.0 in August 2006. Many more versions would follow, with version 1.4.1 as the latest, stable release. You can download the latest version of jquery from the official web site at http://jquery.com. Not only will you find the downloadable files there, but you ll also find the documentation, FAQs, tutorials, and much more information you can use to make the most out of jquery. Besides downloading the library from the jquery web site, any new web site you create using the ASP.NET Web Site template already contains a Scripts folder with the necessary jquery files. You see later how to add jquery files to your site manually. Because the jquery library adds to the size of your web pages, it should be a deliberate choice whether or not you include it in your site. When adding the jquery library to your site, you have a few choices to make. Choosing the Location for Your jquery Reference To include jquery in your web site, you have a couple options: 1. Add a reference to the jquery library in just the web pages or user controls that require it. 2. Add a reference to the jquery library in the master page of your site so it s available in all pages. Both methods have their own advantages and disadvantages. Adding a reference to the jquery library in just the pages that need it helps keep the size of your pages down a bit. When your users browse only to pages without jquery, they ll never have to 2

download the library file. Once they ve downloaded the file, the browser will cache a copy of it, removing the need to download it again on subsequent visits to pages. Adding the reference to jquery in the master page of your site is quite convenient, because all pages based on this master page automatically get access to the jquery functionality. However, this results in a small performance hit on the first page of your site because the library needs to be downloaded from the server. Because the jquery library is quite small, you typically want to include the library in the master page. Besides the location where you add your jquery file, you also have a few options with regard to the way you include the file. Different Ways to include the jquery Library Because the jquery library consists of a single file with JavaScript code, you can embed a reference to the library in a page, user control, or master page using the standard <script> syntax: <script src="filename.ext" type="text/javascript"></script> It s important to use a separate closing </script> tag because some browsers will choke if you use a self-closing tag. I prefer to store all my client-side script files in a Scripts folder in the root of my site, so a reference to the jquery library (called jquery-1.4.1.min.js) will end up like this: <script src="/scripts/jquery-1.4.1.min.js" type="text/javascript"></script> You can also embed the reference inside the ScriptManager control that you have added to the master. The ScriptManager control has a <Scripts> child element that lets you register JavaScript files that will be added to the final page in the browser. In its simplest form, a JavaScript file registered in the ScriptManager looks like this: <asp:scriptmanager ID="ScriptManager1" runat="server"> <Scripts> <asp:scriptreference Path="~/Scripts/jquery-1.4.1.min.js"/> </Scripts> </asp:scriptmanager> 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 3

http://code.google.com/apis/ajaxlibs/. The advantages of using online versions of external libraries are improved performance and lowered bandwidth for your servers. Since 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. In the following exercise, you add the jquery library version 1.4.1 to the master page. Your First jquery Page In this exercise, you add the jquery library to the master page so it s available to all pages in your site. 1. Start by adding a new Scripts folder to the root of the site in Visual Web Developer. 2. Next, open the folder where you extracted the downloaded code. If you followed the instructions in the Introduction of this lecture, the file jquery-1.4.1.min.js is the actual jquery library and jquery-1.4.1-vsdoc.js is a documentation file for IntelliSense and is used only in the context of VWD. Finally, jquery.updnwatermark.js contains a plugin for jquery and is discussed toward the end of this lecture. Your Solution Explorer should now look like Figure 1. Figure 1 3. Next, it s time to add the library to the site s master page so the pages in your web site have access to the jquery library. To do this, open the file Frontend.master from the MasterPages folder and switch it to Markup View if necessary. Locate the ScriptManager control and add the following bolded markup to it: <asp:scriptmanager ID="ScriptManager1" runat="server" EnablePageMethods="true"> <Scripts> <asp:scriptreference Path="~/Scripts/jquery-1.4.1.min.js" /> </Scripts> </asp:scriptmanager> If your ScriptManager didn t have a separate closing tag yet you should add one now (and remove the slash (/) from the opening tag) or the code won t be added correctly. 4. Save and close the master page because you re done with it for now. 4

5. To try out the jquery library, create a brand new Web Form in the Demos folder based on your custom template. Call the page jquery.aspx, and set its Title to jquery Demo. 6. With the new page open in Markup View, add the following code to the Content block for cpmaincontent: <asp:content ID= Content2 ContentPlaceHolderID= cpmaincontent runat= Server > <input id="button1" type=" button" value="button" /> <script type="text/javascript"> $(document).ready(function() { $('#MainContent').css('background-color', 'green') $('#Button1').click(function() { $('#MainContent').css('background-color', 'red').animate({ width: '100px', height: '800px' }) </script> </asp:content> Just like many other programming languages, JavaScript (and thus jquery) is quite sensitive to missing quotes, brackets, and parentheses, so make sure you type this code exactly as shown here. Note that while typing; IntelliSense pops up, helping you complete the code, and giving you information about various methods and parameters in a tooltip. If it doesn t pop up, make sure you added the right <Scripts> element to the master page. Also, try saving and closing all open documents and then reopen jquery.aspx. 7. Save the changes to the page and then press Ctrl+F5 to open it up in the browser. Notice how the background color of the MainContent div has turned to green. Click the button and notice how the background color changes to red and how the MainContent element changes size, ending up with a width of 100 pixels and a height of 800 pixels. 5

How It Works Although the effects shown in this exercise aren t that fancy, a lot is going on under the hood to make this example work. To understand how it works, first look back at the master page where you added a reference to the jquery library: <asp:scriptmanager ID="ScriptManager1" runat="server" EnablePageMethods="true"> <Scripts> <asp:scriptreference Path="~/Scripts/jquery-1.4.1.min.js" /> </Scripts> </asp:scriptmanager> This tells the script manager to include a script element pointing to the jquery library. If you look in the HTML source for the page in the browser you should see the following script element: <script src="../scripts/jquery-1.4.1.min.js" type="text/javascript"></script> This in turn tells the browser to download the jquery-1.4.1.min.js file from the Scripts folder, giving your page access to all functionality included in the jquery library. The next thing to look at is the code in the jquery demo page. First, you added a standard <script> block that can contain JavaScript. Inside this block, you added some jquery code that is fired as soon as the browser is done with loading the page. Everything between the opening ({) and closing (}) curly braces are executed when the page is ready: <script type="text/javascript"> $(document).ready (function () { // Remainder of the code skipped </script> Because the jquery code interacts with the elements on the page, you often have to wait until the entire page has loaded so the elements you re programming against are available. Adding jquery code like this is a standard practice to delay execution of the code until the entire page is ready. The code that is executed when the page is ready consists of two parts. The first line of code sets the background color of the MainContent div to green: 6

$('#MainContent').css ('background-color', 'green') This code gets a reference to the MainContent div element and then calls a css method to change the background color to green. Remember $get from the previous lecture that gets a reference to an element in the page by its id in the client-side ASP.NET AJAX Library? In this example, $('#MainContent') is jquery s equivalent, but as you see later, it s much more powerful. The second part sets up a click handler for the HTML button you added to the page. Inside the click handler you see some code that changes the background color of the MainContent div to red, and changes the height and the width of it using a fluid Animation: $('#Button1').click (function () { $('#MainContent').css ('background-color', 'red').animate ({width: '100px', height:'800px' }) Again, you learn more about how jquery is able to find the button and the div element and how the css and animate methods work later in this lecture, so don t worry too much if none of this is making a lot of sense right now. When you click the button in the browser, the MainContent s background color is changed to red, and then its width and height are changed to 100 and 800 pixels, respectively. When you typed the jquery code you may have noticed you got help from IntelliSense. As soon as you typed $(you got a tooltip explaining the information you can pass to this function. Likewise, IntelliSense helps you find and complete the css method and the various arguments you need to pass to it as shown in Figure 2 (which shows the tooltip under the IntelliSense list to better accommodate the width of this book). IntelliSense for jquery works through the extra file jquery-1.4.1-vsdoc.js you added to the site. VWD scans the solution for files ending in vsdoc.js, parses them, and then uses the documentation it finds in them to build up the IntelliSense list. 7

Figure 2 The reason for the separate documentation file is to keep the size of the original jquery library down. Without the documentation, the library is only 70KB; with the documentation the file size increases to 230KB. You should use the vsdoc file only for development in VWD and never include a link to it in your pages because it doesn t add any value in the browser compared to the real library file. Because of the large size of the documentation file, you re wasting valuable bandwidth and time if you use that file instead of the real library file. JQuery Core Most of the jquery code you write will be executed when the browser is done loading the page. 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 tree-like 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 jquery code), the change is reflected in the page in the browser. If you execute your jquery 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. Fortunately, it s easy to postpone the execution of your code until the DOM is ready using the ready function in jquery. You ve already seen the ready function at work in the previous Try It Out, but it s shown here again now that you better understand what it s used for: 8

$(document).ready (function () { // Code added here is executed when the DOM is ready. Any code you add between the opening and closing curly brace is executed when the page is ready for DOM manipulation. JQuery also comes with a shortcut for the ready function to make it easier to write code that fires when the DOM is ready. The following snippet is equivalent to the preceding example: $(function () { // Code added here is executed when the DOM is ready. Because jquery code is often specific to a page, it makes sense to add the code to the end of just the pages that require it. To make this a little easier, you can add a ContentPlaceHolder in your master page especially for this purpose. The pages that use this master page then have an easy location to write jquery code. You see how to do this in the next exercise. In the previous jquery example you saw some code that selected the MainContent div and the button in your page. However, jquery comes with a lot more options to select specific elements in your pages. These options are discussed next. Selecting Items Using jquery In jquery 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') Between the quotes (you can use single or double quotes, as long as you use the same type on each end) you enter one or more selectors, which are discussed later. The $ method returns zero or more elements that you can then influence using one of the many jquery methods. For example, to apply some CSS to all h2 elements, you use the css method: $('h2').css ('padding-bottom', '10px'); This applies a padding of ten pixels at the bottom of all headings at level two in the page. The cool thing about many of the jquery methods is that, besides applying some design or behavior, they return the matched set again. This enables you to call another method on the same matched set. This concept is called chaining, where you use the 9

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: $('h2').css('font-size', '40px').fadeOut(5000); // timeout is in milliseconds. Basic Selectors JQuery selectors enable you to find one or more elements in your page s document object model so you can apply all sorts of jquery methods to these elements. The great thing about jquery selectors is that you already know how they work. Rather than inventing a new technique to find page elements, the designers of jquery decided to use an existing selector-based syntax that you are already familiar with: CSS. Remember the CSS selectors from lecture 5? You can use the exact same ones in jquery. The Universal Selector Just as its CSS counterpart, the universal selector matches all elements in your page. To set the fontfamily of each element in your page to Arial, you use this code: $('*').css('font-family', 'Arial'); The ID Selector This selector finds and retrieves an element by its id, the same as you would do in CSS. For example, to set the CSS class for a button called Button1, you use this code: $('#Button1').addClass('NewClassName'); When this code sets the CSS class (using the addclass method), the standard CSS rules apply. That means that for this code to work and change the appearance of the button, the NewClassName class needs to be available to the page, either through an external CSS file or by an embedded style sheet. The Element Selector This selector gets a reference to zero or more elements that match a specific tag name. For example, this code turns the text color of all headings at level two to blue: $('h2').css('color', 'blue'); The Class Selector The class selector gets a reference to zero or more elements that match a specific class name. Consider this HTML fragment: 10

<h1 class="highlight">heading 1</h1> <h2>heading 2</h2> <p class="highlight">first paragraph</p> <p>second paragraph</p> Notice how two of the four elements have a CSS class called Highlight. The following jquery code changes the background color of the first heading and the first paragraph to red, leaving the other elements unmodified: $('.Highlight').css('background-color', 'red'); Grouped and Combined Selectors Just as with CSS, you can group and combine selectors. The following grouped selector changes the text color of all h1 and h2 elements in your page: $('h1, h2').css('color', 'orange'); With a combined selector, you can find specific elements that fall within some others. For example, the following jquery touches just the paragraphs that fall within the MainContent element, leaving all other paragraphs alone: $('#MainContent p').css('border', '1px solid red'); To get a feel of the selectors in jquery and the affects you can apply to the matched set, the next exercise shows you how to use some of the selectors and apply some animations to the matched sets. 11