Getting started with jQuery and jQuery UI – Back to Basics

Posted by: Suprotim Agarwal , on 2/18/2015, in Category jQuery and ASP.NET
Views: 46757
Abstract: A quick introduction to jQuery and jQuery UI for beginners. If you are already using jQuery, use this article to foster your basic knowledge of jQuery.

jQuery and jQuery UI - Getting Started

Since you are reading this Getting started guide on jQuery and jQuery UI, I am assuming you are either a designer, who is intrigued by the interactivity that jQuery can provide; or a programmer who plans on using jQuery and seeks to understand how to use it in her/his projects. Think of this article as a starting point for those who want a quick introduction to jQuery. I have also shared some additional resources in this article that you can use to strengthen your jQuery fundamentals.

For those who are already using jQuery in their projects; this article will foster your basic knowledge of jQuery.

The Absolutely Awesome jQuery Cookbook which contains scores of practical jQuery/jQueryUI recipes you can use in your projects right away.

With the context set, let us discuss a common challenge that you as a JavaScript developer might have faced, or are dealing with at present, or are most likely to encounter in the near future.

Say in a project, you have used JavaScript to validate a Form. Your validation logic is good and soon the news spreads across different teams in the organization. They have a similar requirement and want to reuse the same validation logic, in their projects as well. So you decide to save your validation logic as a library to be reusable by others. Now as a JavaScript developer, you know the amount of time and efforts it took you to build such a library. In addition to the time spent in building this library, you now also have to maintain it - officially or unofficially. Some of the challenges during maintenance could be regularly updating the library to remove repetitive code, add new features, best practices, resolve performance issues and worst of all, deal with cross-browser issues. The onus to make the library magically work, is on you!

And this is just Form Validation we are talking about! Almost every project out there has different UI requirements like fluent interfaces, fancy UI stuff like ajaxified Image galleries, Accordions, Dropdowns, Drag drop requirements, Animation effects and so on. Many a times a designer also has to assume the role of a developer and build all these functionalities in a website.

So why jQuery?

Writing JavaScript can be hard. Writing JavaScript that works cross-browser is harder. Wouldn’t it be nice if someone wrote a library for us that contains a large number of utility functions (including validation); that is regularly tested, upgraded and maintained by a community of experienced developers and designers? jQuery, is one such popular library that works well both for designers and developers. jQuery intends to make JavaScript programming more fun and easier to write. Since it uses CSS syntax to search and manipulate DOM elements on the page, a designer finds a lot of familiarity with the language.

If you are a seasoned developer, you can get as complex with jQuery as you like. With jQuery, you can accomplish tasks in a single line of code, which could otherwise take many hours and hundreds of lines of programming.

Note: JavaScript is a language. jQuery is a library, not a language. jQuery is JavaScript.

Setting Up jQuery in your Project

Let us get started by downloading the library from www.jquery.com/download . You will observe at the time of this writing that there are two major branches of jQuery to choose from – jQuery 1.X and jQuery 2.X.

Note: The jQuery team has announced version 3.0 which supports the Promises/A+ specification and has some animation improvements. Don’t worry as all the examples created using jQuery 1.X and jQuery 2.X should run without any issues in the newer version. jQuery 1.11.X will be succeeded by jQuery Compact 3.0 and jQuery 2.X will be succeeded by jQuery 3.0.

jQuery 1.X supports almost all the versions of Firefox, Chrome, Safari, Opera, and Internet Explorer (from v6 onwards). However jQuery 2.X drops the support for Internet Explorer 6, 7, and 8. This makes 2.X smaller in size and better performing. A general rule of thumb is that for a wider reach, use jQuery 1.X, as there are still many who are using the older versions of IE. However, if you are developing an intranet site, and if your company does not use older versions of IE; it’s best to use jQuery 2.X.

In this article, we will be using jQuery 1.11.X however the examples should run without any issues on jQuery 2.1.X as well.

You will also find compressed and uncompressed versions of jQuery on the official site. The uncompressed version (over 275 KB) is intended for development stage; whereas the compressed version (around 94 KB) is minified by removing whitespaces, tabs, line-breaks, comments and shortening variable names. This makes it useful for the production stage, as it saves a reasonable amount of bandwidth due to its smaller size. A minified JavaScript file can be identified by the appearance of .min in the filename; so jquery-1.11.1.min.js indicates that this file is the minified version of jQuery-1.11.1.js

You can also use a Content Delivery Network (CDN) to load jQuery. To understand CDN, read jQuery CDN with Fallback options and Best Practices.

Working with jQuery

Although you can create and run the examples of this article using Notepad; one of the most important tools for web development is an Editor, which can speed up your development efforts by providing features like intellisense, code snippets and so on. I have used Visual Studio 2013 Express for this article , which is available for Free at www.visualstudio.com/en-us/products/visual-studio-express-vs.aspx. Another popular editor is Sublime Text http://www.sublimetext.com/2 which works on Windows, OSX and Linux.

Once you have download the editor of your choice, to set up your first webpage that uses jQuery, follow these steps:

1. Create a folder called scripts in your project. Download jQuery 1.11.1.js and put it in the scripts folder.

2. Create a new page called ‘GettingStarted.html’ at the root of the project. Write the following markup:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Getting Started with jQuery</title>
</head>
<body>
    
</body>
</html>

3. Now include jQuery in your page in the <head> tag as shown here:

<head>
    <title>Getting Started with jQuery</title>
    <script src="../scripts/jquery-1.11.1.js"></script>
</head>

and save the file.

Make sure to check Point 4 of Important Tips Every jQuery Developer Should Know that talks about the different places you can include jQuery in your webpage, and its pros and cons.

4. Once you’ve referenced the jQuery file in your page, you’re ready to add your own scripts that take advantage of jQuery.

When the page loads in the browser and before we start running JavaScript on it, we want to wait till all of the document elements (DOM) on the page have finished loading. The browser emits an event when the DOM is loaded. You can tap this event and write code that is only executed when that event fires. This is done in jQuery using $(document).ready(){}.

<head>
    <title>Getting Started with jQuery</title>
    <script src="../scripts/jquery-1.11.1.js"></script>
    <script>
        $(document).ready(function () {
            // your logic goes here
        });
    </script>
</head>

$() is the $ function and is the entry point to the wonderful world of jQuery. $() can also be written as jQuery() but since $() is a shorthand for the jQuery function, everyone prefers to use it. The $(document) passes the document variable to jQuery. This document variable contains a reference to all the HTML elements on the page (DOM) and fires a ready event. The ready() function is a built-in jQuery function that waits until all the elements in a page finish loading and starts executing code within the curly braces { }.

One place where jQuery() syntax can be used instead of $() is in projects where jQuery is not the only JavaScript library that uses the $ notation. If there are other JavaScript libraries like jQuery that uses the $ notation, it can cause problems. However in such cases, you can make jQuery relinquish control of the $ by calling the jQuery.noConflict method.

Alternatives to $(document).ready()

We can call the ready() function on the document object in two additional ways:

Using $().ready()

<script>
    $().ready(function () {
        // your logic goes here
    });
</script>

Using the jQuery shorthand $(handler)

<script>
    $(function () {
        // your logic goes here
    });
</script>

I use the jQuery shorthand whenever I can.

A common practice followed by developers is to include jQuery code at the bottom of the page, just before the closing </body> tag, so that it doesn’t delay the content loading. It is a good practice to follow, as by having your scripts at the bottom of the page, you can completely avoid the use of $(document).ready(). I however for the sake of readability, am going to use jQuery in my <head> tags in this article..

Now that we know how to handle the document ready event, let us write some code. In the <body> element, add the following HTML structure:

<body>
    <div id="main" class="container">
        Content of the Main Div
        <p id="para1" class="content">Content of Para 1</p>
        <p id="para2" class="content">Content of Para 2</p>
        <p id="para3">Content of Para 3</p>
    </div>
</body>

The structure is very simple. We have a bunch of paragraphs within a div with id=main. We will use jQuery to access and manipulate some of these elements. Let us say we want to add a border to para2, here’s how to do it in jQuery. Add the following code in the <head> section:

<script>
    $(function () {
        $('#para2').css('border', '1px solid #ff0000')
    });
</script>

Observe I have used the jQuery shorthand $(function () {} here. In the code, we have used the jQuery ID selector to select a paragraph with id=para2. The ID selector is characterized by the # sign prepended to the element's ID attribute value, in our case #para2. In case you wanted to select all paragraphs having class="content", you could use a class selector in the following manner.

$('.content').css('border', '1px solid #ff0000')

We have also used the jQuery css() function to set the border to 1px solid red. Save the file and browse the page in your favorite browser. You will see the following:s1-add-border

Although this is a very simple example, observe how jQuery made JavaScript more fun and easier to write; even for designers who do not have much of a programming background. For example, compare the following two syntaxes for selecting an element by its ID:

Using pure JavaScript:

document.getElementById("para2");

Using jQuery library:

$('#para2')

Behind the scenes, jQuery uses the JavaScript function document.getElementById(). Suddenly any designer who knows how to select elements with CSS, can easily transfer that knowledge to JavaScript, by using jQuery.

Live Demo: http://www.jquerycookbook.com/demos/S1-Concepts/1-GettingStarted.html

If you are absolutely new to jQuery, I hope this example has given you a basic idea of getting started with jQuery. However to get up and running with jQuery and use it in your projects, this example is not enough. I highly recommend you to use http://learn.jquery.com/ to explore some jQuery basics before you move ahead.

Once you have gone through the basics, also refer to the jQuery style guide at http://contribute.jquery.org/style-guide/js/

Working with jQuery UI

jQuery UI is a library of user interface plugins, built on top of jQuery. These plugins provide user interface elements like date pickers, drop-down menus, tabbed panels, effects, widgets, and themes to quickly build highly interactive web applications with a consistent look and feel —all with a few lines of programming! These widgets are highly customizable, so should you get creative; you have the extensions points available with you to do so!

To get started with jQuery UI, download the library from http://jqueryui.com/download/ and unzip the contents of the downloaded files. At the time of this writing, jQuery UI 1.11.2 is the most active stable version to download. Check the website to see if a newer version has released and use that in your projects.

s1-jqueryui

If you are on the download page, observe that it gives us a range of different options for selecting the components in their respective groupings (UI Core, Interactions, and Widgets). If you scroll to the bottom of the page to the Theme section, we can choose from one of the 24 different predesigned themes that we want to use; to beautify our page. Overall the entire download package can be tailored to our particular requirements.

For the time being, download the complete library which contains everything we need; including the JavaScript and CSS files, themes, as well the latest version of the core jQuery library itself. The file will get saved as jquery-ui-1.11.2.custom.zip on your machine. Note that the version of the library will differ from the one shown here, depending on the latest version available at the time of your download.

Once you have downloaded the jQuery UI files, copy the jquery-ui.js, jquery-ui.css and images folder in your project. Put jquery-ui.js in the scripts folder we created earlier. Similarly create a new css folder in the project and drop jquery-ui.css in it. Make sure that the images folder is in the same location as the .css file.

Note: On production servers, always use the minified files—the ones with min in their names.

Create a new page called ‘GettingStarted-jqueryui.html’ and now reference the jQuery UI css file in your web page, in the following manner:

<link href="../css/jquery-ui.css" rel="stylesheet" />

If you have some additional css that you have to use for your website, then add the jQueryui css before your custom css. This way, you can override some jQueryui css rules in your custom stylesheet and also ensure that if a newer version of the jQueryui css file is available, your overrides will remain intact in your custom css; whenever you choose to replace the older jQueryui css file with the new one.

As a best practice, reference your CSS files before you reference the JavaScript files.

Now reference the jQuery and the jQuery UI JavaScript files. Since the jQuery UI file depends on jQuery, you need to make sure the jQuery file loads before the jQuery UI file.

<script src="../scripts/jquery-1.11.1.js"></script>
<script src="../scripts/jquery-ui.js"></script>

Once again; on production servers, always use the minified files.

Now that you are ready with the setup, you can start using jQuery UI controls. For our example, we will use the autocomplete jQuery UI widget. The Autocomplete widgets provides suggestions while you type into the field.

An <input> element can be specified as an autocomplete widget. When a user starts typing data in the <input> field, the autocomplete widget provides suggestions based on the entered data in the form of a drop-down list with items. This dropdown is created at runtime. The source of the items in the dropdown can be a JavaScript function, array or even a URL that returns a JSON string. Here’s the markup and code for the autocomplete example:

<head>
    <title>Getting Started with jQuery UI</title>
    <link href="../css/jquery-ui.css" rel="stylesheet" />
    <link href="../css/custom.css" rel="stylesheet" />
    <script src="../scripts/jquery-1.11.1.js"></script>
    <script src="../scripts/jquery-ui.js"></script>
    
    <script>
        var cities = ["Mumbai", "Bengaluru", "New York", "Rome", "Seattle",
                      "Calgary", "Sydney", "Helsinki", "Tokyo", "London",
                      "Paris", "Dubai", "Singapore", "Perth", "New Zealand"];

        $(function () {
            $("#cities").autocomplete({
                source: cities
            });
        });
    </script>
    
</head>
<body>
    <div>
        <label for="cities">Cities Name: </label>
        <input id="cities">
    </div>
</body>

The <input> element with the ID set to cities, acts as an autocomplete widget here. The autocomplete widget is enabled on the <input> element using the autocomplete() method. We have only used the source option in this example and have set it to a JavaScript array—cities. There are several other options like minLength, delay etc. that can be set on the autocomplete widget. Please refer to the jQuery UI Autocomplete widget documentation at jqueryui.com/autocomplete/ .

When the user starts typing data in the input textbox, items are filtered from the array and displayed in the drop-down. The screenshot here displays suggestions when the user types the alphabet ‘P’.

s1-autocomplete

Live Demo: http://www.jquerycookbook.com/demos/S1-Concepts/1.1-GettingStarted-jqueryui.html

This was a simple example to show you the simple set up, and usefulness of the jQuery UI widgets. In a future article, we will see how to use the jQuery UI autocomplete widget with a remote data source and also explore some additional options.

Every jQuery UI effect, interaction, and widget is different and there’s no one set of instructions to follow. In the forthcoming articles, we will cover some jQuery UI widgets in depth and also see how to customize these widgets to suit our requirements. Trust me, you will enjoy using these widgets in your projects, as much as I enjoy writing about them.

Some popular commercial alternatives to jQuery UI are KendoUI, Wijmo and jQWidgets.

jQuery Mobile

The official jQuery Mobile site describes it as “a HTML5-based user interface system designed to make responsive web sites and apps that are accessible on all smartphone, tablet and desktop devices”. jQuery Mobile is out-of-scope for this article and I briefly mentioned it for the sake of completion. If you are interested in it, you can refer to www.jquerymobile.com for additional information.

Once you are familiar with jQuery and its selectors, make sure you read Important Tips Every jQuery Developer Should Know

I hope you enjoyed reading this introduction to jQuery and jQuery UI and will consider using it in your projects. Make sure to check out my new book The Absolutely Awesome jQuery Cookbook which helps you gain hands-on experience with the jQuery API.

Check out the next article Getting started with jQuery $.ajax() – Back to Basics

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by William Michael Martinez on Monday, March 2, 2015 2:32 PM
JavaScript critical error at line 8, column 1 in http://localhost:58216/Content/themes/base/jquery-ui.css

I get this error trying to use the datepicker, if I continue I get the same or similar error on the first line of every ui.'plugin'.css file.
JavaScript critical error at line 8, column 1 in http://localhost:58216/Content/themes/base/jquery-ui.css

SCRIPT1002: Syntax error

My project is MVC 4 just to learn the jquery I've followed several posts that didn't help even though they were helpful to others, I've commented out all of the css files except jquery-ui-core, ...ui.css and .all.css,

These are on the last lines of the body in my layout file:
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/jqueryui")
        @Styles.Render("~/Content/themes/base/css")
        @RenderSection("scripts", required: false)

I down loaded my ui files on Feb, 21...
I was able to get the above example working in asp.net, I'm assuming the same for the date picker...I'm a fairly experienced programmer in asp.net and learning pretty well in MVC
Does anyone have any suggestions, I would greatly appreciate your help...
  
Comment posted by Suprotim Agarwal on Monday, March 2, 2015 9:11 PM
@William This thread will help you out:
http://forums.asp.net/t/1879457.aspx?MVC4+with+jquery+ui+datepicker