JavaScript and jQuery for Designers

JavaScript and jQuery offer mission-critical tools to front-end developers and designers. Understanding the capabilities of these tools will allow you to work more efficiently and implement features you might otherwise think are out of reach.

In this guide, we'll take a brief look at JavaScript and then dive into jQuery. By the end, you'll know the tools available to you, and have access to resources you can use to develop the technical skills necessary to add JavaScript and jQuery to your next project.

JavaScript

JavaScript is a programming language built into every modern web browser. Along with HTML and CSS, it is the third-leg in the modern web technology triad.

JavaScript is a high-level general programming language that can be used for a wide variety of scripting tasks both on and off the web. The primary way designers use JavaScript is to power user interactions. Styling changes and AJAX calls are two examples of user interactions that can be powered with JavaScript. Let's look at each briefly.

Changing Style with JavaScript

While styling of a webpage is generally the domain of cascading style sheets (CSS), JavaScript can be used to manipulate CSS. Styles can be manipulated directly by selecting an element and using the style property, like this:

<div id="my-div">Contents of My Div</div>
<script>
  document.getElementById("my-div").style.backgroundColor = "blue";
</script>

That bit of JavaScript grabs the element with an id of my-div and applies a background color of blue. While directly manipulating CSS with JavaScript is useful, if you want to change a bunch of styles all at once it's a lot easier to include those styles in your site CSS, and then apply the styles using JavaScript. Here's one way this can be done:

<style>
.first-state {
  background-color: #303030;
  color: #fff;
  border: 3px solid #ddd;
  width: 200px;
  height: 200px;
}
.second-state {
  background-color: #ddd;
  color: #333;
  border: 3px solid #333;
  width: 300px;
  height: 300px;
}
</style>
<div id="my-div" class="first-state">Contents of My Div</div>
<script>
  document.getElementById("my-div").onclick = function() {
    this.className = "second-state";
    }
</script>

Now, when the div element with the id attribute of my-div is clicked, the first-state class will be removed and replaced with the second-state class, and the second-state class CSS will be applied.

Click image to toggle animation.

Add Class Animation

Updating Content on the Fly with AJAX

AJAX, which stands for Asynchronous JavaScript and XML, is a technique used to add content to a webpage without refreshing the page. The basic idea is that JavaScript sends data to a web server behind the scenes, receives a response from the server, and adjusts the contents of the webpage based on that response.

That might sound a bit too theoretical, so let's get practical. AJAX makes things like autocomplete features, infinite scrolling, and instant search results possible. In each case, the web page sends data to the web server and loads the response into the webpage without refreshing.

Implementing an AJAX call is a challenging task, and goes beyond basic JavaScript programming. However, as a front-end developer or designer, AJAX is one JavaScript feature you can hardly do without. In the next section, we'll highlight a great AJAX resource.

JavaScript Resources

Now that you know just enough about JavaScript to make you want to learn how to use it, here are three excellent resources that will get you started.

While JavaScript is powerful, jQuery allows you to do alot more with less effort.

jQuery: Write Less, Do More

As the tagline suggests, jQuery is a JavaScript library that makes is possible to do things with a lot less code. So, what is jQuery? Think of jQuery as a bunch of pre-built JavaScript building blocks. Let's look at a basic example. Here's how you would select a an element with the id of my-div first in JavaScript and next in jQuery.

// JavaScript
document.getElementById( 'my-div' );

// jQuery
$( '#my-div' );

Selecting an element by id is pretty easy to do in both languages. However, as you can see, it takes roughly 25 fewer keystrokes to do it in jQuery than in JavaScript.

Adding jQuery to Your HTML Document

You have to load jQuery before you can use it, and there are two simple ways to do so. You can either download jQuery and include a local copy or use a hosted copy such as Google Hosted Libraries.

Here's the code you'd include in your HTML document to load jQuery:

<!--load local copy of jQuery-->
<script src="/js/jquery.min.js"></script>

<!--load from Google Hosted Libraries-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

Note that when you write jQuery, you must load your code after the jQuery core has loaded.

Using jQuery With WordPress

One special consideration to be aware of is that when you use jQuery on a WordPress website you must use jQuery to prefix your code rather than $. There are workarounds you can use to get the $ prefix to work, but failing that, just prefix your code with jQuery, like this:

// Normal jQuery
$( '#my-div' );

// jQuery for WordPress
jQuery( '#my-div' );

jQuery CSS

Just as you can use JavaScript to manipulate CSS, you can do the same thing with jQuery.

We can manipulate classes quite effectively with jQuery. The script below watches for a mouse click on the element with an id of my-div and then removes one class and adds a different class. You can use this code to alternate between two CSS classes.

var myDiv = $( '#my-div' );
$ ( myDiv ).click( function () {
  if ($( '#my-div' ).hasClass( 'first-state' ) ) {
    $( '#my-div' ).removeClass( 'first-state' );
    $( '#my-div' ).addClass( 'second-state' );
  } 
  else if ($( '#my-div' ).hasClass( 'second-state' ) ) {
    $( '#my-div' ).removeClass( 'second-state' );
    $( '#my-div' ).addClass( 'first-state' );
  } 
})

That's helpful, although, we could have done that a lot more easily by using .toggleClass() instead.

var myDiv = $( '#my-div' );
$ ( myDiv ).click( function () {
  $( myDiv ).toggleClass( 'first-state' );
  $( myDiv ).toggleClass( 'second-state' );
})

Let's see that transition in action.

Click image to toggle animation.

Toggle Class Animation
There are many additional jQuery CSS methods. Most notably, the .css() method can be used to manipulate the CSS of a targeted element directly. Other methods, such as .height() and .width() can be used to target specific CSS values.

jQuery Effects

A wide variety of effects are built into jQuery. These effects are strung together with other jQuery methods and functions to control the execution of changes to page elements.

That's a mouthful, so let's look at an example. If we go back to our .toggleClass() function, we can add some effects to smooth out the transition.

var myDiv = $( '#my-div' );
$( myDiv ).click( function () {
  $( this ).fadeOut( 'slow' , function() {
    $( this ).toggleClass( 'first-state' );
    $( this ).toggleClass( 'second-state' );
  })
  $( this ).fadeIn( 'slow' );
&125; )

What that code does is fade the element out, toggle the classes, and fade the changed element back in.

Click image to toggle animation.

Toggle Effect Animation

The fadeOut() and fadeIn() effects are just two of several jQuery effects available. In addition, all effects can employ a number of different options to fine tune their behavior.

jQuery Events

We've already seen one jQuery event several times in this tutorial: .click(), which fires when a user clicks the targeted element. However, there are many additional events available.

Events used to target user action include .click(), .dblclick(), .hover(), .mouseenter(), .mouseleave(), and .mousemove(), which are all fairly self-explanatory. There are also several event handlers that watch for changes to page elements:

  • .change() detects when form elements change. Similarly, .submit() detects when a form is submitted.
  • .focus() is triggered when a targeted element gains focus.
  • .ready() fires as soon as the browser has built the webpage.
  • .resize() triggers code to run when the viewport is resized.
  • .trigger() ties one event to another related event.

There are additional jQuery events we haven't covered in this brief guide. Learn more by referring to the jQuery documentation or the suggested resources.

jQuery UI

jQuery UI is an extension to jQuery that includes powerful UI widgets and tools. Implementing a jQuery UI feature, such as an accordion widget, is trivially simple compared to coding the same feature from scratch.

jQuery UI features can be broken into four categories: widgets, effects, interactions, and utilities. Let's take a look at each. But first, we need to know how to add jQuery UI to an HTML document.

Adding jQuery UI to an HTML Document

You have two options when it comes to loading jQuery UI: download it and include a local copy or include a CDN-hosted copy.

<!--load local copy of jQuery UI-->
<link rel="stylesheet" href="/css/jquery-ui.css">
<script src="/js/jquery-ui.min.js"></script>

<!--load from Google Hosted Libraries-->
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

In addition, keep these points in mind:

  • The CSS stylesheet link should go in the document head.
  • The jQuery UI script should go just above the closing body tag.
  • The jQuery core (jquery.js or jquery.min.js) must be loaded before jQuery UI (jquery-ui.js or jquery-ui.min.js) is loaded.

jQuery UI Themes

When you download a copy of jQuery UI the download builder allows you to include a theme. This is because jQuery UI widgets require default styling. The jQuery UI theme you select defines the default widget styles, and the relevant code is included in jquery-ui.css.

If you do opt for the Google-hosted option, note that the theme name is dropped in just before the file name: .../smoothness/jquery-ui.css. Smoothness is the default jQuery UI theme. You can use any theme by substituting the theme name when building the URL.

In addition, the jQuery UI website offers a ThemeRoller which you can use to build your own theme and include it when you download jQuery UI.

jQuery UI Widgets

Widgets make it relatively effortless to create useful UI elements that would take a mountain of code to create with pure JavaScript and CSS. Let's take a look at some of the most helpful jQuery widgets (click any to be taken to a demo):

  • Accordions allow you to hide information behind a heading and display it by toggling each section open and closed.
  • Tabs are an alternative to accordions. They're a space-saving way to present information.
  • Buttons in jQuery UI are beautiful and consistently presented.
  • A Datepicker can be added to a form to ensure dates are properly selected and formatted.
  • Progressbars provide a visual indication of how much progress has been made toward the accomplishment of a goal.
  • Sliders allow users to select a single value or a range of values when submitting a form.
  • A Spinner adds up and down arrows for entering numbers in a form field.
  • Tooltips can be used to provide field-specific information to form users.

To give you a sense for how easy widgets are to implement, here's all of the code you would need to use to create a set of accordions:

<!-- add the jQuery UI stylesheet -->
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">

<!-- add the accordion content to the page -->
<div id="accordion">
  <h3>Accordion Section 1</h3>
  <div>
    <p>Accordion content. You can use paragraphs, lists, links, whatever.
  </div>
  <h3>Accordion Section 2</h3>
  <div>
    <p>Like I said.
      <ul>
        <li>You</li>
        <li>Can</li>
        <li>Use</li>
        <li>Lists</li>
      </ul>
  </div>
  <h3>Accordion Section 3</h3>
  <div>
    <p>That's it. It's super easy.
  </div>
</div>

<!-- load jQuery and jQuery UI -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<!-- apply the accordion widget to the page content -->
<script>
$( function() {
  $( "#accordion" ).accordion();
} );
</script>

As you can see, the HTML is much longer than the few lines of jQuery required to turn the HTML into accordions.

Click image to toggle animation.

jQuery UI Accordions Animation

jQuery UI Effects

Most of the methods in this category are expansions of core jQuery methods. For example, if you want to manipulate classes, the .addClass(), .removeClass(), and .toggleClass() methods are all available in jQuery UI, along with an additional method, .switchClass(). The difference is that in jQuery UI these methods include additional options, such as the ability to add transition effects directly to the method itself.

Let's look at an example. Remember when we used .fadeIn() and .fadeOut() to change the appearance of a div? Well, we can create a much nicer effect with a lot less code by using jQuery UI.

var myDiv = $( '#my-div' );
$( myDiv ).click( function () {
  $( this ).toggleClass( 'second-state' , 1000 );
} )

Here's that transition in action.

Click image to toggle animation.

jQuery UI Toggle Class Animation

A few additional effect methods you'll want to know include:

  • The .show() method removes display: none; from the targeted element.
  • The .hide() method adds display: none; to the targeted element.
  • The .toggle() method will switch the targeted element between a visible and hidden state.

jQuery UI Effect Animations

There are 15 different effect animations with names like blind, bounce, clip, drop, and explode. Let's look at an example of the slide effect.

var myDiv = $( '#my-div' );
var myButton = $( '#my-button' );
$( myButton ).click( function () {
  $( myDiv ).toggle( "slide" );
} )

In this case, we added a button to slide the div on and off the screen. Let's see what our div looks like when hidden with that bit of jQuery.

Click image to toggle animation.

jQuery UI Hide Animation

These jQuery transition effects can be applied to the .show(), .hide(), and .toggle() methods. The jQuery UI website includes an effect preview tool which you can use to decide which effect best fits your implementation.

Easing jQuery UI Transitions

The jQuery core includes just two easings: swing and linear. However, jQuery UI adds more than 20 easings. Let's take a look back at our implementation of the .toggle() method, this time adding in two different easings.

var myButton = $( '#my-button' );
$( myButton ).click( function () {
  $( '#first-div' ).toggleClass( 'second-state' , 2000 , 'easeInOutQuad');
  $( '#second-div' ).toggleClass( 'second-state' , 2000 , 'easeInOutExpo');
} )

In this example, there are two divs. Both will transition to the second state in 2 seconds. However, each will use a different easing. Let's take a look.

Click image to toggle animation.

jQuery UI Easing Animation

jQuery UI Interactions

Interactions are a set of jQuery UI methods that allow website and app users to select and move page elements. There are five jQuery UI interactions. Clicking on any of the links below will take you to a demo of each interaction at the jQuery UI website.

  • The Draggable interaction allows users to reposition a web page element by dragging and dropping it with their mouse.
  • The Droppable interaction works hand-in-hand with the draggable interaction. To use it, both a draggable and a droppable item must be available on the webpage. When the draggable item is dropped onto the droppable item, an action is triggered.
  • Resizable does exactly what you think it should: it makes a page element resizable.
  • Selectable can make the items in a list selectable either by clicking on them one at a time, or by holding down Ctrl or clicking and dragging across multiple items to select multiple items at once.
  • Sortable makes it possible to rearrange list items in any order.

jQuery UI interactions aren't the sort of thing you'd expect to implement on the average website. However, if you're creating an interactive web app, game, or complex form, these interactions will come in handy.

jQuery UI Utilities

jQuery UI can be extended and the widget factory is the utility used to do so. Widget factory allows you to package up multiple jQuery UI methods, styles, and functions into a single reusable widget.

If you're familiar with object-oriented programming, it might be helpful to think of jQuery UI widgets as objects. So, a jQuery UI accordion is actually an object of the accordion class. What the widget factory allows you to do is to define new classes of widgets and then use that class to create multiple objects, much in the same way you create a class and reuse it over and over in OOP.

Another useful jQuery UI utility is the .position() method. This method allows you to define the position of any element relative to another element or user action. The method is pretty simple once you get the hang of it. Let's look at an example.

$( '#second-div' ).position({
  my: 'left top',
  at: 'right bottom',
  of: '#first-div'
});

That bit of code says that the left top corner of the element with the id of second-div should be positioned at the right bottom corner of the element with the id of first-div, like this:

jQuery UI Position Animation

In addition, items can be positioned based on user actions. Let's adjust the code to use the position of the mouse rather than the first div to determine the position of the second div.

$( document ).mousemove( function (event) {
  $( '#second-div' ).position({
    my: 'center',
    of: event,
    collision: 'fit'
  })
})

That code adds a listener for the .mousemove() event that will be triggered anytime the mouse enters the document. When that happens, the .position() of the targeted div will be determined based on the position of the mouse.

Let's see it in action.

Click image to toggle animation.

jQuery UI Position Mousemove Animation

jQuery Mobile

jQuery Mobile is another extension of the jQuery library. It is used to create touch-optimized responsive websites and apps.

When thinking of jQuery Mobile, the emphasis really should be placed on touch-optimized. There are many core jQuery and jQuery UI methods and events that just aren't applicable to a mobile device, and jQuery Mobile addresses that shortcoming. Unlike jQuery UI, which can be used to power just one or two facets of a website, jQuery Mobile is designed to be an all-or-nothing solution for touch-based responsive websites and apps.

The library includes a large array of responsive, touch-optimized buttons, datepickers, form elements, swipe events, navigation elements, tables, tabs, sliders, and more. In addition, jQuery Mobile includes a ThemeRoller.

The challenge with using jQuery Mobile is its all-or-nothing approach. It is designed to create full-replacements for desktop versions of websites and apps. If you'd rather have a single site or app that works on all devices, jQuery Mobile is not what you're looking for. If you do use jQuery Mobile for an app or website that works on all devices — touch-enabled and not — you will need to find a way to switch jQuery Mobile on and off by detecting the device type, size, and presence of a touchscreen.

Resources

We already pointed out a few places where you can learn JavaScript. If you don't already know some JavaScript, develop those skills before diving into jQuery. Once you have some JavaScript under your belt, the following resources will get you up to speed with jQuery, jQuery UI, and jQuery Mobile.

  • jQuery Foundation Learning Center is the official (and one of the best) places to learn jQuery. Here you'll find a chapter-based course that covers the basics, events and effects, AJAX, plugins, and more. When you're ready, you can also learn how to use jQuery UI and jQuery Mobile.
  • Learn jQuery From Scratch is a project-based tutorial that will help you gain confidence as a jQuery programmer.
  • CodeCademy jQuery Course teaches you jQuery syntax, as well as how write basic functions, modify DOM elements, use events, and implement effects.
  • jQuery Fundamentals by Bocoup is an ebook with a built-in JavaScript console so you can try out the code right in the browser. It covers jQuery basics, traversing and manipulating DOM elements, events, effects, and AJAX.

Summary

JavaScript and jQuery are two of the fundamental technologies of modern front-end development. Extensions to jQuery, jQuery UI and jQuery Mobile, add a wealth of widgets, interactions, methods, effects, and touch-optimized tools. Mastering these languages and libraries will make you a better designer, as you incorporate a broader range of features into your designs, and a better developer, because you'll be able to build powerful, interactive web apps without wasting any keystrokes.


Further Reading and Resources

We have more guides, tutorials, and infographics related to coding and website development:

What Code Should You Learn?

Confused about what programming language you should learn to code in? Check out our infographic, What Code Should You Learn? It not only discusses different aspects of the languages, it answers important questions such as, "How much money will I make programming Java for a living?"