jQuery and jQueryUI

Les Pinter



How to use jQuery | What else can you do with jQuery? | jQuery UI | Accordions | jQuery Mobile | Conclusion

Ever seen those cool web pages with tons of special effects - fades, dissolves, rollups, tooltips, and lots of others? Chances are they were done using a free JavaScript library called jQuery.

jQuery was created by John Resig in 2006, based on Dean Edwards's cssQuery JavaScript library. It's currently maintained by Timmy Willison and Richard Gibson. It's funded by donations, so once you discover that you can't live without it, send them a few bucks.

How to use jQuery

As with most JavaScript libraries, you can reference it inside a <script> tag:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

The associated Style Sheet is at

<link rel="stylesheet" href="https:/resources/demos/style.css">

jQuery libraries are automatically added to generated Visual Studio web applications. Click the button below to view the Solution Explorer windows with jQuery references included by Microsoft. Figure 1 shows the directory structure of an ASP.NET app; Figure 2 shows the expansion of the Content folder, and Figure 3 shows the expansion of the Scripts folder. Obviously, Microsoft thinks pretty highly of this software.


This neat little trick is brought to you courtesy of jQuery. It's just one of a number of effects that are only a small part of what this package does. Here's the code:

Listing 1: Show/Hide toggle

<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
...
<script>
$(document).ready(function () {
	$("#btnShowHide").click(function () { $("#libs").fadeToggle(); });
} );
</script>
</head>

<body>
<button id="btnShowHide" type="button">Show/Hide Solution Explorer contents</button><br />
<div id="libs" style="display: none;" >
<table>
<tr>
<td><b>Fig. 1 - Website folders </b></td>
<td><b>Fig. 2 - <i>Content</i> folder </b></td>
<td><b>Fig. 3 - <i>Scripts</i> folder </b></td>
</tr>
<tr>
<td valign=top><img src="jQuerySolExp01.gif" style="transform:scale(.9); margin-top: -25px;" /></td>
<td valign=top><img src="jQuerySolExp02.gif" style="transform:scale(.9); margin-top: -25px;" /></td>
<td valign=top><img src="jQuerySolExp03.gif" style="transform:scale(.9); margin-top: -25px;" /></td>
</tr>
</table>
</div>

The <script src=""...> reference pulls jQuery into your web page when it loads. You can download and read the code. This is a "minified" version with the carriage returns and other whitespace removed for faster loading. Your browser doesn't care about whitespace. So if you're determined to read the code, get the non-minified version.

Scripts are loaded into your user's browser, and if they're big, it can be slow. Scripts can either be located on your own server, or on the jQuery server. Microsoft Visual Studio generates copies of all of these script files in your directories, so that you can run and test them without having to be connected to the Internet. But you can also link to the ones located at jQuery.com or GoogleAPIs.com.

The "$" is a surrogate for the jQuery library. You can mix JavaScript with statements that reference jQuery, because it's all just JavaScript.

The purpose of "$(document).ready(function definition)" is to tell jQuery to wait until the page has loaded before loading and/or processing scripts. It's the normal way of declaring functions that will be used within the page.

$("#btnShowHide") is a selector that tells jQuery to find the object with the id "btnShowHide". The rest of the code associates the defined function with the button's click event. When clicked, the <div> element with id="libs" is "fade-toggled" - it's gradually hidden, then redisplayed when clicked again.

Selectors can be pretty much anything you can think of. "#" prefixes references to IDs, while "." prefixes class references. Ordinarily you would use classes if more than one element will be affected by a jQuery or JavaScript operation. You can select a particular ID, all elements that include a class="className" reference, all "<p>", "<li>" or "<tr>" elements, or any combination thereof. There's even a way to specify every other line of the third <table>. The 2015 Derek Banas YouTube tutorial includes a particularly deep dive into selectors.

Selectors can be nested. You can find all "<li>" tags that are contained within a div called "MainPoints" by specifying "$("MainPoints li"). This will change their color to red:

Listing 2: Nested selectors:

<!doctype html>
<html
<head>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
</head>
<body>
<div id="MainPoints">
<p>These are the main points:
<ul>
  <li>First
  <li>Second
  <li>Third
</ul>
</div>
<script>
$(document).ready(function () {
  $("#MainPoints li").attr('style', 'color: red');
});
</script>
</body>
</html>

Copy and paste to a filename on your desktop with a name that ends in ".html" and then double-click on it to run it. The three lines in the list will be displayed in red. Note that you can put this script anywhere in either the <head> or the <body> section; it will run when the document loads. But you can also attach the code to any event on any object.

What else can you do with jQuery?

You can select based on the presence of or absence of key word or phrases, or the value of tag attributes. You can conditionally add text to, or remove text from, your html. You can conditionally load a text file containing html using AJAX (Asynchronous JavaScript And XML) without reloading the entire page, which is faster and "smoother". You can cause a page to look one way on a full-size monitor, and completely different on an iPhone (called responsive web page design).

The jQuery page at W3Schools.com has a bunch of examples and tutorials:

jQueryUI (user interface)

A major use of jQuery is to make the user interface more interesting. For this purpose, an additional library called jQueryUI has been developed, together with a massive CSS (Cascading Style Sheet) file to accompany it. Here's an example of what it does. You'll need to add links to the relevant jQueryUI libraries in the section:

Listing 3: jQuery UI example:

<head>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
</head>
...
<p>Date: <input type="text" id="datepicker"></p>
<p><Label for="datepicker" />

Date:

Clicking on the textbox will display a calendar:

Fig. 4 - jQuery UI DatePicker

That's a pretty good improvement over requiring the user to type in numbers and slashes, hoping they'll get the date right.

There are any, many more features in the jQueryUI library. (Note that it comes with its own CSS file, so be sure to add links to both if you use both jQuery and jQueryUI.) In addition, available widgets include Accordion, Menu, Slider, Tabs and many, many more. If you've thought about it, it's probably there.

Accordions

A useful effect is an "accordion" that contains several headings, but displays only the contents of one of them at a time. With jQuery UI, it's very, very simple. Here's an example:

Section 1

Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer ut neque.

Section 2

Sed non urna. Donec et ante. Phasellus eu ligula. Vestibulum sit amet purus.

Section 3

Nam enim risus, molestie et, porta ac, aliquam ac, risus. Phasellus pellentesque purus in massa.

Section 4

Cras dictum. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.

and here's the code:

Listing 4: jQuery Accordion:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Accordion - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <style>
  	h4 { background-color: lightblue; border: 2px black solid; width: 200px; border-radius: 10px; }
  	.acc { background-color: ivory; font-size: 14pt; font-family: tahoma; }
  </style>
</head>
<body>

<script>
$( function() {
$( "#accordion" ).accordion();
} );
</script>
<div id="accordion">
  <h4>Section 1</h4>
  <div class="acc">
    <p>Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer ut neque.</p>
  </div>
  <h4>Section 2</h4>
  <div class="acc">
    <p>Sed non urna. Donec et ante. Phasellus eu ligula. Vestibulum sit amet purus.</p>
  </div>
  <h4>Section 3</h4>
  <div class="acc">
    <p>Nam enim risus, molestie et, porta ac, aliquam ac, risus. Phasellus pellentesque purus in massa.</p>
  </div>
  <h4>Section 4</h4>
  <div class="acc">
    <p>Cras dictum. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>
  </div>
</div>

</body>
</html>

jQuery Mobile

Finally, if you want to target devices of all shapes and sizes, jQuery Mobile is for you.

CSS 3 added "@media" tags to group style settings to be applied based on the size of the viewport. They look like this:

@media screen and (max-width: 600px) {
  body {
    background-color: olive;
  }
}

@media queries are useful when you want to apply CSS styles depending on a device's general type (such as print vs. screen), specific characteristics (such as the width of the browser viewport, or environment (such as ambient light conditions). Given the variety of devices available today, media queries provide tools for building websites and apps that will adapt to whatever hardware your user is using.

Here's a way to change the layout of your menus based on the device screen width:

/* The navbar container */
.topnav {
    overflow: hidden;
    background-color: #333;
}

/* Navbar links */
.topnav a {
    float: left;
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

/* On screens that are 600px wide or less, make the menu links stack on top of each other instead of next to each other */
@media screen and (max-width: 600px) {
    .topnav a {
        float: none;
        width: 100%;
    }
}

The demo shows the result of shrinking the window size:

jQuery Mobile adds many other features that provide the sort of user experience that we've come to expect from mobile devices. You should download the source and experiment with it. Around 40% of all hits on web pages last year occurred on phones and tablets. It's what's next.

Conclusion

There are many, many additional effects and capabilities in jQuery and jQueryUI. In addition, dozens (hundreds?) of plugins are available that extend jQuery to do amazing things. And the price is right. Download jQuery at jQuery.com.

❑❑❑