Tag Archives: jQuery tutorial

It is the Best of Times and it is the Worst of Times for Programmers

screen shot 2013-03-05 at 1.07.11 pm

Across the past six years, the US economy was mired in a recession. Yet throughout it all, there was one bright spot: the IT and programming job market. It seemed as if no matter how bad things got in the economy as a whole, there was always demand for IT skills due to a lack of supply.

And while the IT job market remains strong, it continually puts workers in a good news/bad news situation. The good news, of course, is that there are plentiful jobs, especially when compared to other segments of the economy. The bad news is that the competition is so fierce, the path of change so great, that workers can’t be complacent.

If their skills decay or if they remain idle for even six months, there will inevitably be other programmers – both in the US and abroad – who’d be happy to fill the void. The bottom line? Don’t be complacent. Continue to grow and learn. Expand your skills by taking a Java tutorial video, MVC tutorial, or a jQuery tutorial!

Thousands of developers worldwide use LearnNowOnline to gain the technical skills they need to succeed on the job and advance their career.

Soften Your Look with jQuery

As mentioned in a previous blog post, Microsoft made two commitments when it decided to embrace jQuery as its one and only client-side JavaScript library. First, they were going to replace their Ajax Library with jQuery in every appropriate ASP.NET Web technology, including both Web Forms and MVC applications. Second, they would contribute plugins and other extensions to the jQuery Library, primarily by adapting their work on enhancements for the Ajax Library to the jQuery Library. These contributions might end up in the core jQuery Library, as official jQuery extensions, or, as a last resort, freely distributed, open source extensions.

In this article, we’ll discuss one such extension.

Creating Rounded Corners

rounded corners in AJAX

Putting rounded corners on elements is a desirable feature to soften the look of a Web page. But it is surprisingly hard to do well across all browsers, both because there are so many ways to accomplish the effect and so many variations among browsers. Web designers have long resorted to using images, even though CSS and other Web technologies support rounded corners. ACT has a nice RoundedCorners extender that applies the effect to HTML elements, letting you vary the appearance by changing the radius of the corner, which corners are rounded, and other options, giving a lot of flexibility for creating a nice page appearance. The Figure below shows the RoundedCorners extender demo from the ACT sample pages, with options set to round the upper right and lower left corners of the image.

Rounded corners seems to have been an area of particular creativity for jQuery plugin developers, probably because of the cross-browser issues and the lack of a single right way to achieve the effect. The result is a lot of plugins that let you get as creative as you want. We chose one of the simpler plugins to use on the Toolkit page, shown in the Figure below. The first box is a plain, square div element and the second has rounded bottom left and upper right corners using the Cornerz plugin for “bullet proof corners.” The plugin has a few options such as to set the border and background color, set the radius, and select which corners to round. But overall it is a pretty simple plugin that does its job quite well.

rounding the corners of a div element

The page uses the following HTML code for the Rounded Corners section. It is very simple markup, using a couple of div elements that each contain a p and cite elements.

The page uses a twain class to style the div elements, setting padding and the background color. Padding is important for most rounded corner plugins, providing room around the text to round the corner. You could have a border of a different color—as is commented out in the style below—and the border would be rounded as well.

Then the page includes a single JavaScript statement to round the corners, shown in the following code. It calls the cornerz method, passing two optional arguments. fixIE attempts to overcome a problem with some inline elements in Internet Explorer due to a wrong reporting of width, and the second specifies that only the top right (tr) and bottom left (bl) corners should be rounded.


ldn-expertdkielyThis post is an excerpt from the online courseware for our ASP.NET 4.0 AJAX and jQuery Using Visual C# 2010 course written by expert Don Kiely.

Pulling Out the Big Gun: The Ajax Method

Screen Shot 2012-10-18 at 11.46.55 AM

 

All of the Ajax features in jQuery are convenience methods that make using Ajax fairly easy for the most common scenarios. But when those convenience methods don’t work for you, you can pull out the big Ajax gun in jQuery: the ajax method. This is the method that all of the convenience methods ultimately use to make the actual call to the server. They do this by performing all the setup necessary and setting default values for various arguments that work for the particular Ajax task at hand.

You can make use of the ajax method directly to handle the scenarios not easily handled—or not handled at all—by the convenience methods. It has the deceptively simple syntaxes shown in the following code, taking just one or two arguments, url and options. With the first syntax option, you can pass the URL for the Web service and optionally follow it with as many option settings as you need. Or you can just pass a value for the options argument, one of which could be the url. This method is the embodiment of the saying that the devil is in the details, and providing the right options for what you want to do is the details you need to wade through to make the method work for you.

Let’s look at a simple example of using the ajax method by rewriting the ‘Hello World’ sample below. Here is the code from that sample:

The HelloWorldAjax.html page in the sample project uses the ajax method directly to make the Ajax call to the server. It uses the type option to make a GET call and the url option to specify the location of the Web service. Like the get and post methods, the ajax method is a utility function that doesn’t directly update a matched set of elements, so the method call uses the success event option to define a function to update the div elements on the page with the response text. This anonymous function uses the text method of the response object to extract the text from the XML returned from the Web service method and the html method to update the div elements.

The figure below shows the results of clicking the Get Info button on the page, where the code updates the three div elements on the page.

As you can see, using the ajax method is more complex than using the load method, both because you have to provide appropriate option values as well as because the method doesn’t directly update a matched set of elements. You have to write a function for the success event to update the page.

ldn-expertdkielyThis post is an excerpt from the online courseware for our ASP.NET 4.0 AJAX and jQuery Using Visual C# 2010 course written by expert Don Kiely.

The jQuery User Interface Library: Small but Mighty

jQuery UI Site

One of the major benefits of jQuery is that the core library is quite small, just 83KB for the minified version. Packing so much functionality into such a small package is no mean feat, and one of the primary ways that the jQuery does it is by keeping the library focused on the most important, core features needed to make client-side Web programming with JavaScript as easy and productive as possible. Over the years since its introduction, there have been many proposals to add great new features to the library, but each idea has been closely scrutinized and included only when it made sense and made the library stronger. A feature that would only be cool wouldn’t make the cut. The result of all this dedication to keeping the core jQuery library small and tight has paid off with a versatile library that doesn’t impact Web page performance too heavily.

But this has left a lot of great ideas for jQuery features out in the cold, and many have become widely used plugins and other extensions. And although the jQuery library provides plenty of tools for making great Web user interfaces, there are so many other things that you can do with jQuery as the base. So the jQuery UI library was born to bring together many user interface features built on jQuery. The UI library is not part of the core library and is much more than a jQuery plugin. It is an official extension to jQuery developed and supported by the jQuery team.

The jQuery UI library consists of four broad categories of extensions:

  • Interactions support ways of letting the user interact with elements on a Web page, including the ability to drag and drop elements, resize them, make them selectable in various ways, and allow the user to sort elements in whatever order they want.
  • Widgets (yes, that’s what they call them!) are a collection of user interface components, including a date picker, dialog boxes, tabs, and a slider, and more.
  • Effects in the UI library go far beyond the animations available in the core jQuery library. You can animate color transitions, class changes (as opposed to just a set of properties you define in the animate method), and 15 effects that go well beyond the fading and sliding in and out supported in the core library.
  • Utilities that acts as a grab bag of other features. As of this writing, the only utility available supports element positioning that goes well beyond the positioning features in CSS. Near term additions are planned to support templating and a data model (features that Microsoft is working on), globalization, and others.

The UI library makes heavy use of CSS styles to create themes for the UI features, primarily interactions and widgets, so that they have a consistent look and feel. There are more than 20 standard themes that you can download along with the UI library, which you can tweak to fit the appearance of your Web pages. You can write the CSS code by hand or use the ThemeRoller tool on the jQuery UI Web site to make changes to a theme and download it, ready to drop into your Web site.

NOTE: As you explore the features of jQuery UI, it is easy to get a sense of why Microsoft so easily abandoned development of their Ajax Control Toolkit, built on their Microsoft Ajax Library. Once they decided to switch to jQuery and support it, it became a no-brainer to also embrace jQuery UI, which is far richer than the Ajax Control Toolkit. At this time Microsoft doesn’t ship the UI library with any of their tools, but we suspect that will be a logical next step in the evolution of Microsoft’s support for jQuery.

Downloading the jQuery UI Library

The jQuery UI Library is huge if you include every feature. It is unlikely that any single Web site project will use them all, so the library is split into many files and you can use whatever you need in a Web page. To help customize the library, the download page of the jQuery UI Web site, shown in the Figure below, lets you build a custom download package with only the elements you need. You can also select a theme as a starting point for customizing it to your needs.

The download page lets you select the elements you need, and makes sure that all dependencies are covered. For example, the Core component in the UI Core section is required for all other components, and you can’t uncheck that check box if you have any other components selected. The result is that the custom library you download has everything you need for the features you want. Links at the top of the page let you forego customizations and let you download the entire library or individual themes directly.

TIP: One downside of the jQuery UI download page is that there is no easy way— that we’ve been able to find, anyway!—to download all of the themes together. You can click the themes link in the Quick Downloads section at the top of the page and download the themes one by one, but that is tedious at best. Or you can go to the jQuery UI blog and go to the post that announced the release of the UI library version you’re using. There is usually a link there to a file with all the themes.

Once you download the custom jQuery UI library and unzip it, you’ll find an index.html file and three directories.

  • The index.html file contains a recap of what you built and a demo page that shows the features of the theme you selected, if any, as shown in the Figure below. Pay attention to the specified version of the jQuery library that this version of the UI library works with.
index.html page
  • The css folder contains the CSS and image files needed for the theme you selected. You can copy the theme folder into your Web site project and use it directly, but make sure you keep the images folder as the child of the folder that contains the .css file. Otherwise, you’ll have to change many, many links in the stylesheet to point to the new location of the images.
  • The js folder contains both the script file for the jQuery UI library as well as the core jQuery library. You can use that version of the core library or, usually, a later version. Usually you’ll copy the UI library file,
    jquery-ui-1.8.9.custom.min.js, to the scripts file in your Web
    site (the version number on your file may be different). This is a customized version of the script file that includes everything you need for the features you selected.

TIP: The version of the UI library in the js folder is the minified version of the library. During development and as you’re learning the library, you may want to use the Quick Downloads link at the top of the download page to get the development version of the component files. These have comments and whitespace to make it easier to read and understand.

  • The development-bundle folder contains demos, documentation, licenses, and lots of other resources to explore. As you’re learning the UI library, it would be well worth your time to explore what this folder contains.

Once the theme and script files are in your Web site folders, you can proceed to use them like any other CSS and script files, including them in a Web page using link and script elements. These elements will look something like the following, which we took from one of the sample pages in the custom UI library download that used the default ui-lightness theme (and uses an older version of the jQuery library, since version 1.5 had just been released and the download page hadn’t yet been updated). Even though the UI library consists of many .css and .js files, the custom download greatly simplified using them by combining them into single files of each type.

ldn-expertdkielyThis post is an excerpt from the online courseware for our ASP.NET 4.0 AJAX and jQuery Using Visual C# 2010 course written by expert Don Kiely.

 

Adding and Removing Page Elements with jQuery

Not only can you change the appearance of the page with jQuery and update the content of elements on the page, you can even add and remove elements to and from the page dynamically! Now, we’re talking real power: you can essentially rewrite the page on the fly using jQuery. Of course, you have long been able to do this using plain JavaScript, but it would take a lot more code and work, and you’d have to deal with nasty cross-browser issues.

The html method you learned about in the last section has rudimentary support for adding new elements to a page, embedded within a string. But that technique requires that you build a string containing the new elements. The difference between that technique and the ones you’ll learn about in this section is that with these new techniques you can add a new element anywhere on the page, before or after existing elements, without building a string first. It’s much more flexible and efficient this way.

jQuery has a few methods for adding elements, and one to remove elements. (There are a few others that can add and remove content, but this section focuses on the primary, most straightforward techniques.)

  • The insertBefore and insertAfter methods insert the new element you define immediately before or after all the elements in the wrapped set, as the sibling of each element. (A sibling is an element at the same level in the DOM hierarchy, with the same parent element, as another element.)
  • The prependTo and appendTo methods insert the new element you define as the child of each element in the wrapped set, either at the beginning or at the end of the child content.
  • The remove method removes all elements in the wrapped set from the page.

It is important to understand that adding and removing elements change only the in-memory DOM used to render the page, and leave the page source unchanged and unaffected.

One of the many ways you can make use of dynamically adding and removing elements is to handle the case where JavaScript is not available in the user’s browser, whether because the browser doesn’t support it or the user has it turned off. For example, you may build a page like the one shown in Figure 1 that has a highlighted notice at the top of the page along with a second paragraph that JavaScript code removes when the page loads. Therefore, if the browser doesn’t have JavaScript available, the notice and second paragraph remains on the page.

the page when javascript is not available

Figure 1. The page when JavaScript is not available.

For users that have JavaScript available and enabled, there are several changes to the page, as you can see in Figure 2. The JavaScript notice and following paragraph are removed, a secret message appears, a button that can hide content appears, and NOTICE!/END NOTICE! is added to the beginning and end of every paragraph. The page is quite different from its non-JavaScript version!

the page when javascript is available

Figure 2. The page when JavaScript is available and enabled.

If the user clicks the button, code in the page removes both the button and the snarky paragraph about everyone being able to see the content, as shown in Figure 3, leaving behind only the Michael Pollan quote with good advice about eating habits. Non-JavaScript users don’t have the capability of removing that content. As you can see the page demonstrates a number of different scenarios for controlling content through code using jQuery.

The following HTML code defines the starting content of the page in the body section (we’ve removed some of the text content to make it easier to focus on the structure of the page). Notice that one p element has a class associated with it, and the other two have an id value.

The noJavaScript CSS class, defined in the page in a style element rather than in a separate stylesheet, adds the red border and yellow background to the first paragraph.

The first block of JavaScript code in the page makes all of the initial changes to the page when it loads, and is enclosed in the jQuery ready function. Keep in mind that none of this code executes when JavaScript is not available.

The first part of this block of code uses the remove method to remove the highlighted notice and the following paragraph, using selectors appropriate to select those elements. That’s how easy it is to remove elements from the page! And if the selectors selected multiple elements, all those elements would be history.

The next statement dynamically adds the paragraph with the secret that only users with JavaScript enabled will be able to see. Notice that this statement uses a new form of the jQuery function, passing the HTML markup in a string as the sole argument to the function. This causes jQuery to parse and select the markup—as it does with a regular selector—but doesn’t yet insert it into the DOM. The insertAfter method takes care of that task, inserting the new paragraph immediately after the h1 element as its sibling. The argument to the method is a selector that selects the elements on the page that you want to place the new paragraph after. On this page, it will insert a single instance of the paragraph after the sole h1 element on the page.

NOTE: If there were more than one h1 element on the page, the insertAfter method call would add the new paragraph immediately after each of the h1 elements. You can easily test this by adding more h1 elements on the page. If you really only want one instance of the paragraph on the page, you’d need to change the selector that you pass to the insertAfter method, such as by using the :first filter.

The next statement dynamically adds the button to the page. The string defining the button is again passed to the jQuery function, but this time the code uses the insertBefore method to insert it immediately before the p element with an id value of everyone.

The final two statements in the first code block take care of adding the NOTICE!/END NOTICE! to the beginning and end of all p elements on the page. It is important to understand that at this point, there are only two p elements on the page; the others have been removed. That’s why back in Figure 2 only two paragraphs are visible. This code uses the prependTo method to insert NOTICE! at the beginning of each paragraph, and the appendTo method to add END NOTICE! at the end of each paragraph, with spaces needed to keep the new text separate from the old.

The second and final code block on the page wires up the click event function of the Remove Non-Sensitive Content button, buttonRemove, that the code added dynamically in the other code block. The event function does two things: removes the paragraph that contains “ hip ” (with leading and trailing spaces to avoid matching that string embedded in words) and removes the button.

The one big thing that is different in this code is that it passes a jQuery filter to the first remove method. Without that filter, the statement would remove all p elements on the page. But by filtering the wrapped set passed to the remove method by the jQuery function in that statement, it filters the p elements to be removed to only those that contain the hip string. In this statement you could easily have included the filter in the selector in the jQuery function, but in more complex, chained statements that might not have been possible. JQuery is a very flexible library indeed.

NOTE: The code that wires up the buttonRemove click event function didn’t have to go into its own jQuery ready function. It could have gone into the other code block, immediately after inserting the button to the page. It’s just personal style to keep event function definitions separate to make the code a bit cleaner and easier to maintain, but there really is no compelling reason to do so. Do it however works best for you.

One of the important lessons in this section, besides how to dynamically add and remove elements, is that the jQuery selector has uses far beyond the jQuery function. You’ll definitely want to make sure you practice creating selectors in a wide variety of scenarios so that you are able to create selectors to get references to exactly the page elements you want.

WARNING! The elements you remove using the remove method still appear in the page source. So users with JavaScript can still see the message for people without JavaScript, and those without JavaScript could see the secret embedded in the code in the page. So this is not a technique for protecting content that you want only certain people to see.

ldn-expertdkielyThis post is an excerpt from the online courseware for our ASP.NET 4.0 AJAX and jQuery Using Visual C# 2010 course written by expert Don Kiely.

jQuery: Compressed vs Uncompressed, the Choice is Yours

When you go to the jQuery Web site to download jQuery files, you’ll find that you have two file options, shown in Figure 1: a production version (compressed) and a development version (uncompressed) of the core jQuery library. The files sizes for version 1.5 are quite different: 29KB and 207KB.

jquery

Figure 1. The download panel on the jquery website.

TIP: You can download older versions of jQuery using the Download link on the jquery.com Web site (not shown in Figure 1) as well as plugins and other extensions.

The difference in the two files is that the development version is human readable with lots of whitespace and generous amounts of comments to help you understand the code. Figure 2 shows the first few of the 8,177 lines of code in the file open in the Visual Studio code editor. We recommend that you use this version of the file, named jquery-1.5.js, while you learn jQuery and in development. That way, you can use the Visual Studio JavaScript debugger to step into jQuery both to understand how jQuery works and to understand why your code might not be working the way you expect (and to perhaps find a bug in jQuery). Loading a 207KB file on your local development machine should take no time at all, so it won’t slow down your coding.

jQuery library file

Figure 2. The development version of the jQuery library file.

Then, when you’re ready to deploy your site, use the 29KB production version in the file named jquery-1.5.min.js, where “min” stands for minified. This file has had all of the unnecessary whitespace removed, variable names shortened, and other compression tricks applied to get the size of the file as small as possible. As you can see in Figure 3, the file consists of the readable comments at the top of the file, and a single line of code; you’ll see that line is 83,996 characters long if you scroll all the way to the right. If you scroll through the one line of code, you’ll find that it is almost impossible to follow the logic. We humans just weren’t built to process such condensed data! But a browser knows just what to do with it.

production version of the jQuery library file

Figure 3. The production version of the jQuery library file.

The benefit of the production version is that users have to download a much smaller file when they load your page, and you save a bit on your bandwidth bill. Even though the browser will cache the file for subsequent page views, this will mean that the initial page load will be noticeably faster, particularly over slower connections.

TIP: You can get the size of the development version even smaller if you use gzip compression in your Web site.

This post is an excerpt from the online courseware for our ASP.NET 4.0 AJAX and jQuery Using Visual C# 2010 course written by expert Don Kiely.

7 Benefits of jQuery

jquery1

 

jQuery makes using a Web page’s DOM (document object model), adding effects to the page, animating elements, and executing Ajax calls to the server extremely simple, hiding the complexity of the underlying JavaScript. There are a number of benefits to using jQuery instead of writing your own raw JavaScript or building your own library.

  • jQuery is lean and mean. Please forgive the cliché, but it is an apt way to describe the library. The minimized size of version 1.5 of the library is a mere 83KB, only 29KB when gzip’d. That is probably smaller than a single photo on many Web sites, and the browser only has to download and cache it once for use across all your pages. If you use a content delivery network (CDN), the user’s browser can cache it across many Web sites rather than download it for each. jQuery packs a lot into a very small size.
  • One of the primary benefits of jQuery—a benefit shared with some other JavaScript libraries—is that it seamlessly handles crossbrowser issues. JavaScript implementations differ among browsers to varying degrees, and it can cause a developer to prematurely and severely age to get everything working across browsers with JavaScript. Relax: the authors of jQuery have done most of the work for you.
  • jQuery uses a simple, clean, powerful syntax that makes it easy to select the DOM elements on the page you want to change with JavaScript and allow you to chain actions and effects together for efficient code. It is quite common to replace a dozen or more lines of JavaScript with a single line of jQuery code. jQuery uses the CSS (Cascading Style Sheets) version 3 selector specification for selecting elements, so you don’t have to learn a different syntax to use jQuery. This assumes, of course, that you’re familiar with the CSS3 syntax.
  • jQuery is highly extensible. As mentioned earlier, the core jQuery library is kept tight and focused, keeping out non-essential features. It also provides a plugin framework that makes it easy to extend jQuery, and there are both official jQuery plugins as well as thousands from third parties. This way your page has to download only the specific set of features it needs. Any time you need a feature not included in the core jQuery library, there is a good chance that someone has already written a plugin that does what you need.

TIP: You can find a list of available plugins at jquery.com, the home of jQuery, with user ratings to help you find the best ones.

  • jQuery supports building pages using unobtrusive JavaScript, an approach to using JavaScript in Web pages. Among other things, unobtrusive JavaScript is concerned with the separation of functionality between a Web page’s structure/content and presentation. This keeps nuggets of code out of HTML elements on the page, such as with event attributes such as onclick. Instead, you wire up event code in a script block, keeping the behavior implemented in code separate from the structure of the page.
  • One of the goals of jQuery is to make things that are hard in JavaScript easy when using jQuery. So jQuery includes many utility functions to do things like trim strings, parse JSON data, check whether one DOM element is within another, and search array elements using a filter.
  • jQuery is one of the most widely used JavaScript libraries available, with support from some of the most heavily trafficked Web sites in the world. According to the jquery.com Web site, Google, Amazon, IBM, Microsoft, Twitter, Dell, CBS News, Bank of America, and many others use it on their Web sites, and it is in use in many open source projects including Mozilla, DotNetNuke, and WordPress. Such widespread use ensures that jQuery will receive active development support for years to come, and a vibrant user community has formed around the library.

If you want to add rich user interactivity or Ajax features to your Web site, there really is no reason not to consider jQuery. Once you learn what jQuery can do and how small and efficient it is, it’s easy to understand why Microsoft abandoned its own Ajax Library in favor of jQuery! Even if you begin using jQuery and find some highly specialized situation that the library doesn’t support, you can always fall back to writing your own custom JavaScript for that one situation.