jQuery To Scroll To A Specific Element

I thought I’d share a useful snippit of jQuery code for scrolling to a specific element on a page.

$('html, body').animate({
    scrollTop: ($('#element').offset().top)
},500);

We use the .animate() method to scroll to the top of #element, over a period of 500 milliseconds.

jQuery To Scroll To The First Element With A Specific Class

A practical use of this could be in validating a form and you want to scroll to the first error for the user to correct. Assuming all elements with problems have been given the class of error, we can scroll to the first one using jQuery’s .first() method before chaining on .offset() and the property top as before.

$('html, body').animate({
    scrollTop: ($('.error').first().offset().top)
},500);

Now, go get scrolling!

Updating A List In JQuery Mobile

Are you using jQuery Mobile and trying to manipulate a listview?

I was trying to do this earlier, adding new <li> elements to a <ul data-role="listview">. However, none of the new elements were looking correct, or having the right styles applied.

The solution is to tell jQuery Mobile to refresh the list and apply the styles.

If your <ul> list has an id of wibble you could use the following…

$('#wibble').listview('refresh');

Your list will now have the correct styling applied.

Centering A Header Image In jQuery Mobile

I needed to replace the header text in a jQuery Mobile application with an image.

I first tried wrapping the image in the <h1> tag, but that adds quite a large margin and cuts off some of my image.

The solution I used was to instead add a wrapper div that centers everything in it. My header ended up looking like this…

Header

center-wrapper is a custom style defined like this…

.center-wrapper {
  text-align: center;
}
.center-wrapper * {
  margin: 0 auto;
}

There may be a better way to do this, but this works for now.

Draw Something Solver – The Platform

I have been putting some more thought into how to build my Draw Something Solver.

I have decided as I use Draw Something on my iPhone 4S, the solver should really run on there. This means coding using Objective C, or using HTML 5 and JavaScript.

As I haven’t written an HTML and JavaScript application for a while, and as it’s more fun, I think this should be the technology to use.

The only difficulty I can see is in getting screenshots from Draw Something into the application. Phonegap looks like it exposes some functionality to achieve this in JavaScript, so it looks like a good idea to use this as well. It also gives me the bonus of being able to create a native iOS application I could choose to upload to the App Store if I wanted, and also look a producing a version for Android in the future.

To give the application a native look and feel, using something like jQTouch or jQuery Mobile would make sense. jQuery Mobile has quite a lot of buzz at the moment and I’ve not had the opportunity to use it before, so I think I’ll try it out in this project.

Creating A New Element With jQuery, With Or Without A Plugin

UPDATE: Whilst this remains an interesting example of creating a simple plugin, I no longer recommend this way of creating elements in jQuery. Instead just pass the html you want to use into jQuery directly as a string, e.g. var myH1Element = jQuery("<h1>My H1 Test</h1>");.

One function that seems to be missing in jQuery is to create new elements outside of the current DOM.

There is a good reason for this, normal vanilla JavaScript has the function createElement to do the job for you.

To create a new h1 element for example, we can do the following.

var myH1Element = document.createElement('h1');

We can easily combine this with jQuery to set the text inside for example…

jQuery(myH1Element).text("My H1 Text");

There is one downside, using the standard createElement we’re not able to chain functions with jQuery.

The way around this is to wrap the request in jQuery like this…

jQuery(document.createElement("h1"));

Now we can chain this together as before…

jQuery(document.createElement("h1")).text("My H1 Text");

If you don’t like the look of that, then we could always create a jQuery plugin, and add a createElement function to jQuery.

jQuery.extend({
createElement : function(elementName) {
return jQuery(document.createElement(elementName));
}
});

That must be one of the simpliest jQuery plugins ever!

Now we have extended jQuery with a createElement function we can chain calls to it like this.

jQuery.createElement("h1").text("My H1 Text").appendTo("body");

This will create a new h1 element, add the text “My H1 Text” inside the h1, then append the h1 inside the documents body tag.

Using jQuery And Mootools On The Same Page

While it’s never a good idea to bloat your webpage with too much unneeded content, there are times when you can’t avoid it. One example I came across recently was with my day job’s adoption of jQuery as our official JavaScript framework, I needed to add some jQuery goodness to some blog pages belonging to a certain category in Movable Type. Simple, right?

Well the site in question already used Mootools extensively, so the jQuery would have to run nicely next Mootools and not disrupt existing functionality.

The designers of jQuery have designed for this sort of situation, and have provided a function called noConflict that returns the use of $ to Mootools, or any other framework you may have installed as well.

Here’s some example code to show both jQuery and Mootools running in the same page…

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript"><!--
jQuery.noConflict();
//-->
</script>
<script type="text/javascript" src="mootools-1.2-core-yc.js"></script>

In my Movable Type situation, I am able to use a custom MT tag to make sure jQuery only appears for certain categories. Let’s assume I have a category called jQuery where I need the jQuery library to be imported, the MTIfCategory tag is what I need to guard with…

<MTIfCategory label="jQuery">
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript"><!--
jQuery.noConflict();
//-->
</script>
</MTIfCategory>
<script type="text/javascript" src="mootools-1.2-core-yc.js"></script>

With this in place I can call jQuery functions using the jQuery variable, and MooTools using $ where necessary.

Writing A jQuery Plugin To Stripe A Table

One of the most powerful features of jQuery is it’s plugin architecture. This allows developers to easily extend jQuery’s functionality.

I’ve decided to extend my table striping example code and turn it into a jQuery plugin. If I have a table with an id of test, I want to be able to call a stripe function on it’s selector, e.g. $('#test').stripe();

So how do we build this? Well firstly, as it’s a plugin we shouldn’t really be playing with the $ jQuery object incase our user has disabled it. There is a trick to get around this though…

(function($){
// code here can safely use $
})(jQuery);

What’s happening here? Well we’re using a closure to create an anonymous function into which we pass in the jQuery object. The parameter name we use in this function is $ so we can use this inside safely, even if the user has disabled this variable outside our plugin.
Now we have our $ variable we can get on with building the plugin.

$.fn.stripe = function(options) {
// define our function action here.
}

Here we’ve added a function to jQuery called stripe and told it to reference a fuction we’ve defined. Now we need to add the magic to this function to actually do the striping.

return this.each(function() {
$('/tbody:first>tr:even',this).addClass('even');
$('/tbody:first>tr:odd',this).addClass('odd');
});

As a jQuery selector can run over multiple items, we need to make sure we iterate over each of these. We use jQuery’s built in each function to do this. this refers to the current selector in this case.

Inside, we need to select the first tbody element of the selection, then for each child tr depending if it’s odd or even we set the class of that tr to be either even or odd. This should ensure that nested tables won’t be striped.

That’s great, but what would be even more useful would be the ability to define different class names dynamically so we’re not stuck with the two hardcoded ones.

This is easy to achieve by creating a set of defaults in a private object, passing overrides into our function, and using jQuery’s excellent extend function to merge the two.

var defaults = {
odd : 'dark',
even : 'lite'
};
var options = $.extend(defaults, options);

Now we can either just call .stripe directory, or pass in override options like this, .stripe({odd: 'testdark', even: 'testeven')

Putting this all together, we get the following code for our stripe plugin.

(function($){
$.fn.stripe = function(options) {
var defaults = {
odd : 'dark',
even : 'lite'
};
var options = $.extend(defaults, options);
return this.each(function() {
$('/tbody:first>tr:even',this).addClass(options.even);
$('/tbody:first>tr:odd',this).addClass(options.odd);
});
}
})(jQuery);

A configurable jQuery plugin, in just 13 lines of JavaScript. Marvellous!

Alternating Table Rows With JavaScript And jQuery

One of the most popular stories on this website is on Alternating Table Rows With Template Toolkit And CSS. The example I use is how to stripe alternate rows in an HTML table by applying a seperate class to each row.

As I’ve been learning jQuery lately, I thought I’d update this example to show how to do it using this excellent JavaScript framework.

Firstly, we need to setup our styles. We’ll have a lite and a dark class to use that will just set a different background colour.

<style type="text/css">
.lite {background-color: #ddffff;}
.dark {background-color: #aaffff;}
</style>

We’ll also need an example table.

<table class="stripe">
<tbody>
<tr>
<td>1</td><td>One</td>
</tr>
<tr>
<td>2</td><td>Two</td>
</tr>
<tr>
<td>3</td><td>Three</td>
</tr>
<tr>
<td>4</td><td>Four</td>
</tr>
<tr>
<td>5</td><td>Five</td>
</tr>
</tbody>
</table>

Notice how I have given the table a class of stripe. This is important, I’m going to use jQuery to only select table elements that have this class name, else every table on the page would be striped.

The jQuery to achieve the striping is actually very simple.

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('table.stripe>tbody>tr:even').addClass("lite");
$('table.stripe>tbody>tr:odd').addClass("dark");
});
</script>

Firstly we added the jQuery library to the page. Next we setup our striping code to only run once the DOM is place. This is important as we’re going to be selecting and manipulating over the DOM next. The next two lines apply the lite class to even table rows and the dark class to odd table rows. Let’s look at this in a bit more detail.

The selector $('table.stripe>tbody>tr:even') is easier to explain backwards. We look for even matching tr elements, that have a parent of tbody, that has a parent of table with a class of stripe. The use of the > symbol instead of just a space is to make sure the elements are direct parent and child elements instead of just ancestor and descendant. Why is this important? Well if we used a space any nested tables that happened to have an striped ancestor would also be striped. This isn’t normally what we’d want to happen.