All Levels

Create a Responsive Navigation Menu Using jQuery

With more and more people accessing the web from mobile devices and tablets every day, it's becoming increasingly important for websites to be responsive, and one of the most important aspects of a mobile friendly website is a responsive navigation. Creating a mobile-friendly navigation menu without the use of a plugin might seem like a daunting task, but one can actually be created fairly easily with some media queries and a few lines of jQuery. Start with your standard navigation menu, which can be styled however you like, and probably looks something like this:
  1. <div id="menu">
  3. <ul>
  4. <li><a href="#">Link One</a></li>
  5. <li><a href="#">Link Two</a></li>
  6. <li><a href="#">Link Three</a></li>
  7. <li><a href="#">Link Four</a></li>
  8. </ul>
  9. </div>

Next, you're going to need to add some jQuery to your code.
  1. $("#menu").addClass("responsive").before('<div id="three-lines">&#9776;</div>');

This line of jQuery adds the CSS class responsive to the #menu div. and adds the div #three-lines before #menu.responsive. The #three-lines div is what creates the ☰ character that will replace the navigation menu when the screen gets to a certain width. This line of jQuery won't work properly unless we add some styling. We're going to need a media query to make sure that #menu.responsive becomes hidden when the screen gets to a certain width, and one that allows #three-lines to show up at that same point.
  1. @media screen and (max-width: 700px){
  2. #menu.responsive{
  3. display: none;
  4. }
  5. }
  7. @media screen and (min-width: 700px){
  8. #three-lines{
  9. display: none;
  10. }
  11. }

Now the default navigation menu will display when the browser window is above 700px, but when the window becomes smaller than 700px, it will disappear and the #three-lines icon will become visible. All that's left to do is add one more jQuery function that toggles the navigation menu when the #three-lines div is clicked.
  1. $("#three-lines").click(function(){
  2. $("#menu").toggle();
  3. })

Now when the ☰ icon is clicked, the #menu div will appear. It will disappear if the ☰ icon is clicked a second time. Customize the responsive menu by adding your own styling or effects.

Using jQuery’s .pushStack() for reusable DOM traversing methods

The .pushStack() method has been in jQuery since before version 1.0, but it hasn't received a whole lot of attention outside of core developers and plugin authors. While its usefulness may not be immediately apparent, it can come in really handy in some situations, so I'd like to take a quick look at what it does, how it works, and how we can use it.

pushStack Basics

At its most basic level, the .pushStack() method accepts an array of DOM elements and "pushes" it onto a "stack" so that later calls to methods like .end() and .andSelf() behave correctly. (Side note: As of jQuery 1.4.2, you can pass in a jQuery object instead of an array, but that isn't documented and jQuery itself always uses an array, so that's what we'll stick to here.)

Internally, jQuery uses .pushStack() to keep track of the previous jQuery collections as you chain traversing methods such as .parents() and .filter(). This lets us traverse through the DOM, do some stuff, "back up" to previous collections within the same chain using .end(), and then do something else. Here is a somewhat contrived example:

Read the rest of this entry »

Using jQuery’s Data APIs

In the beginning (well, beginning with jQuery 1.2.3 in early 2008) there was the jQuery.data() API. It offers a way to associate JavaScript data — strings, numbers, or any object — with a DOM element. As long as you manipulate the DOM element with jQuery, the library ensures that when the DOM element goes away, the associated data goes away as well. This is especially important for older versions of IE that tend to leak memory when JavaScript data is mixed with DOM data.

Most jQuery code sets data values using the higher-level .data() API; for example, $("div").data("imaDiv", true) sets a boolean value on every div in the document. This API, in turn, calls down to jQuery.data() with each element to set the value. For completeness, there are also jQuery.removeData() and .removeData() to remove data elements, and jQuery.hasData() to determine if any data is currently set for an element.

Read the rest of this entry »

jQuery.map() in 1.6

Among all of the great fixes and additions to jQuery 1.6, I'm happy to say that jQuery.map() now supports objects! The previous map only supported arrays. With other libraries already offering object support for map, it was a nice addition.

Read the rest of this entry »

Merging jQuery Deferreds and .animate()

Editor's Note: This article originally appeared on danheberden.com.

jQuery’s .animate() method, and the shorthand methods that use it, are fantastic tools to create animations. Creating animations that link together to achieve a particular effect, and do something specific at the end of the animation, can be a painful, messy task. Luckily, we have .queue() for mashing animations together.

But what happens when you want to bridge the gap between ajax requests and animating? When you want to queue a bunch of animations, get data from the server, and handle it all at once, without a crap-load of nested callbacks? That’s when jQuery.Deferred() puts on its cape, tightens its utility belt, and saves the day.

Read the rest of this entry »

Autocomplete Migration Guide

The jQuery Autocomplete plugin got a successor recently, the jQuery UI Autocomplete. In this guide we'll look at the old plugin API step-by-step, and how to migrate to the new API.

At first it may look like the new plugin supports barely any of the old options. We'll see how all the old options can be implemented using the three new options and the six events.

The old plugin had two arguments: data or url, and options. Lets start with that data-or-url argument. With the new autocomplete plugin, you'll just pass the data or url to the source option.

So, with the old plugin you'd have this code:

  1. $("input").autocomplete(["a", "b", "c"]);

And that becomes, easy enough:

  1. $("input").autocomplete({
  2.   source: ["a", "b", "c"]
  3. });

The same applies if you provided a URL as the first argument, although there is a difference between the two plugins for remote data. The old plugin expected a special format with pipes to separate values and newlines to separate rows. That is gone for good, the Autocomplete widget now works with JSON by default. The simplest form is the same as in the example above, an array of string values.

Instead of an array of strings, the widget also accepts an array of objects, with at least a label or value property, or both, in addition to whatever else you need. More on that can be found in the documentation and various demos, eg. the Custom Data demo shows how to use custom properties and even display them.

Lets look through the rest of the options for the old plugin, and what to do with them for the new plugin:

  • autoFill: Gone with no immediate replacement available, for good reasons: The default behaviour when selecting items via keyboard now puts the focussed value into the input, like the Firefox Awesomebar does it. It's not the same as what the autoFill option did, but there should be no need to recreate that effect.
  • cacheLength: There is no built-in caching support anymore, but it's really easy to implement your own, as shown by the Remote with caching demo.
  • delay: Still exists with the same behaviour, but the default is always 300 milliseconds.
  • extraParams: Extra params and all other Ajax related options can be customized by using a callback for the source option. Use $.ajax to send the actual request, with the response callback argument passed to source as the success callback for the $.ajax call. The Remote JSONP datasource demo has an example for that.
  • formatItem, formatMatch, formatResult, highlight: All gone, instead use the source option to either provide the formatted data from your serverside, or implement a custom source to do special formatting. The combobox demo shows how to do that, with a more extensive explanation of that demo right on this site.
  • matchCase, matchContains, matchSubset: All gone, too. The builtin matcher for local data will do a case-insensitive match-contains, everything else has to be implemented on the serverside or using the source option. The combobox linked just above also has an example for that.
  • max: Gone; if your server sends too many items, pass a function for the source option that calls $.ajax and truncates or filters the resulting list.
  • minChars: Still present, but was renamed to minLength. Behaves just the same, even the default is still the same, with minLength: 1.
  • multiple, multipleSeperator: Not built-in anymore, but easy to recreate. There are two demos for this, once with local data, once with remote data.
  • mustMatch: Gone, but easy to implement with the select event. Once more, the combobox provides an example for that.
  • scroll, scrollHeight: These option are gone, but the underlying Menu widget actually has support for scrolling. If you have enough items and specify a height via CSS, the menu will scroll.
  • selectFirst: Similar to autoFill (at the top of this list), this option is gone and has now immediate replacement, nor a need for one. The behaviour for selecting values is solid enough to make this option redundant.
  • width: Gone and not required anymore. The menu will automatically be as wide as the input it completes, or wider, as the content requires. And you can always restrict with width using CSS.

And thats about it. If you're still looking for a particular replacement, take a look at the various events available, and study the use of the source-option within the various demos. If you still have a question, post on the Using jQuery UI forum. If you spot some mistake or see something that can be improved in this article, please let us know in the comments.

Advertise on our network
See our other websites