Category Archives: jQuery

Five Useful CSS/jQuery Coding Techniques For More Dynamic Websites

Interactivity can transform a dull static website into a dynamic tool that not only delights users but conveys information more effectively. In this post, we’ll walk through five different coding techniques that can be easily implemented on any website to provide a richer user experience.

The techniques will allow you to better display difficult content, help users find information more effectively and provide meaningful UI cues without overwhelming the user.

  1. On-page text search
  2. Drag controls for oversized content
  3. Subtle hover effects
  4. Comment count bars
  5. Full-page slider

[Offtopic: by the way, did you already get your copy of the Smashing Book?]

1. On-Page Text Search

E-read-search-instant in Five Useful CSS/jQuery Coding Techniques For More Dynamic Websites

Websites often have search boxes to allow users to find content from their archives. But what if you want to find content on the given page? Information Architects has had on-page text search that provides a great user experience. Let’s recreate this using jQuery.

Mark-Up and Interaction

First let’s build an input box for the search:

1 <input type="text" id="text-search" />

Next we’ll need jQuery to attach a listener to track changes to the input box:

1 $(function() {
2 $('#text-search').bind('keyup change', function(ev) {
3 // pull in the new value
4 var searchTerm = $(this).val();
5 )};
6 });

Here we bound our function to both the keyup and change events. This ensures that our operation fires regardless of whether the user types or pastes the text.

Now, let’s turn to Highlight, a useful and lightweight jQuery plug-in that handles text highlighting. After including the plug-in source, let’s add a highlight() call to our JavaScript:

01 $(function() {
02 $('#text-search').bind('keyup change', function(ev) {
03 // pull in the new value
04 var searchTerm = $(this).val();
06 // disable highlighting if empty
07 if ( searchTerm ) {
08 // highlight the new term
09 $('body').highlight( searchTerm );
10 }
11 });
12 });

In addition to highlighting the given text, we’ve also added a check to make sure the search term isn’t empty (which causes an infinite loop).

This snippet highlights the search query throughout the page, but we can also limit the scope to a given id:

1 $('#myId').highlight( searchTerm );

Or we can search only within a certain element:

1 $('p').highlight( searchTerm );

This text highlighting by default is case insensitive. If you’d prefer case-sensitive highlighting, remove the .toUpperCase() on both lines 21 and 41 of the Highlight plug-in.

Styling the Highlighted Text

Now that the JavaScript is attached, we’ll need to style our highlighted items. The Highlight plug-in wraps the highlighted terms in <span></span>, which we can style with CSS.

First, let’s change the background color and then add rounded corners and a drop-shadow for all browsers except IE:

1 .highlight {
2 background-color: #fff34d;
3 -moz-border-radius: 5px; /* FF1+ */
4 -webkit-border-radius: 5px; /* Saf3-4 */
5 border-radius: 5px; /* Opera 10.5, IE 9, Saf5, Chrome */
6 -moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7); /* FF3.5+ */
7 -webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7); /* Saf3.0+, Chrome */
8 box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7); /* Opera 10.5+, IE 9.0 */
9 }

Although the highlighting is now visible, it still appears a bit tight around the text and could use some padding. But we’ll have to be careful not to adjust the layout of text. These spans are inline elements, and if we simply add padding, the text will shift around on the page. So, let’s include padding with a negative margin to compensate:

1 .highlight {
2 padding:1px 4px;
3 margin:0 -4px;
4 }

Finishing the Interaction

Last but not least, let’s make sure to remove the highlighted text whenever the user edits text in the input box:

01 $(function() {
02 $('#text-search').bind('keyup change', function(ev) {
03 // pull in the new value
04 var searchTerm = $(this).val();
06 // remove any old highlighted terms
07 $('body').removeHighlight();
09 // disable highlighting if empty
10 if ( searchTerm ) {
11 // highlight the new term
12 $('body').highlight( searchTerm );
13 }
14 });
15 });

Here we added a call to remove any text highlighting, which is performed outside of the empty field check. This ensures that the highlight is also removed if the user clears the field.

Although removeHighlight() works well in most browsers, it will crash IE6. This is due to an IE6 bug with node.normalize().

We can get the Highlight plug-in working in IE6 by rewriting this function. Simply replace lines 45-53 of highlight.js with the following:

01 jQuery.fn.removeHighlight = function() {
02 function newNormalize(node) {
03 for (var i = 0, children = node.childNodes, nodeCount = children.length; i < nodeCount; i++) {
04 var child = children[i];
05 if (child.nodeType == 1) {
06 newNormalize(child);
07 continue;
08 }
09 if (child.nodeType != 3) { continue; }
10 var next = child.nextSibling;
11 if (next == null || next.nodeType != 3) { continue; }
12 var combined_text = child.nodeValue + next.nodeValue;
13 new_node = node.ownerDocument.createTextNode(combined_text);
14 node.insertBefore(new_node, child);
15 node.removeChild(child);
16 node.removeChild(next);
17 i--;
18 nodeCount--;
19 }
20 }
22 return this.find("span.highlight").each(function() {
23 var thisParent = this.parentNode;
24 thisParent.replaceChild(this.firstChild, this);
25 newNormalize(thisParent);
26 }).end();
27 };

This new function replaces the standard Javascript normalize() with a custom function that works in all browsers.

2. Drag Controls For Oversized Content

Moscow in Five Useful CSS/jQuery Coding Techniques For More Dynamic Websites

When layout constraints bump up against the need for large images, finding a quality solution can be difficult. Mospromstroy uses a creative technique to handle this situation: a “drag and drop” control bar that allows users to pan through images.

We can accomplish something similar using jQuery UI’s draggable behavior.

Mark-Up and CSS

First let’s set up some mark-up for the content and controls:

1 <div id="full-sized-area">
2 <div id="full-sized-content">
3 Your content here
4 </div>
5 </div>
7 <div id="drag-controls-area">
8 <div id="drag-controls"></div>
9 </div>

Next, let’s apply some basic CSS:

01 #full-sized-area {
02 position: relative;
03 overflow: hidden;
04 width: 800px;
05 height: 400px;
06 }
08 #full-sized-content {
09 position: absolute;
10 top: 0;
11 left: 0;
12 }
14 #drag-controls-area {
15 position: relative;
16 width: 300px;
17 height: 50px;
18 }
20 #drag-controls {
21 position: absolute;
22 top: 0;
23 left: 0;
24 height: 48px;
25 border: 1px solid white;
26 }

Here we applied an absolute position to both the #full-sized-content and #drag-controls, and we also hid any overflow from the large image. Additionally, we applied some arbitrary dimensions to the content and drag controls wrappers; make sure to adjust these as needed.

Building Interactivity With jQuery

Now, let’s use jQuery UI to build the interaction. Begin by including jQuery UI with the draggable module.

Before attaching the controls, let’s resize the drag control box to the right dimensions:

01 $(function() {
02 var $fullArea = $('#full-sized-area');
03 var $fullContent = $('#full-sized-content', $fullArea);
05 // find what portion of the content is displayed
06 var contentRatio = $fullArea.width() / $fullContent.width();
08 // scale the controls box
09 var $controlsArea = $('#drag-controls-area');
10 var $controls = $('#drag-controls', $controlsArea);
12 $controls.css('width', $controlsArea.width() * contentRatio);
13 });

Here, we’ve determined what portion of the content is visible in the content area and then scaled the width of the control box accordingly.

Next, let’s attach the draggable behavior:

01 $(function() {
02 var $fullArea = $('#full-sized-area');
03 var $fullContent = $('#full-sized-content', $fullArea);
05 // find what portion of the content is displayed
06 var contentRatio = $fullArea.width() / $fullContent.width();
08 // scale the controls box
09 var $controlsArea = $('#drag-controls-area');
10 var $controls = $('#drag-controls', $controlsArea);
12 $controls.css('width', $controlsArea.width() * contentRatio);
14 // determine the scale difference between the controls and content
15 var scaleRatio = $controlsArea.width() / $fullContent.width();
17 // attach the draggable behavior
18 $controls.draggable({
19 axis : 'x', // confine dragging to the x-axis
20 containment : 'parent',
21 drag : function(ev, ui) {
22 // move the full sized content
23 $fullContent.css('left', -1 * ui.position.left / scaleRatio );
24 }
25 });
26 });

Here, we’ve attached a draggable event and set a couple options. First, we set axis to restrict dragging to the x-axis, and then we set containment to confine dragging to the parent element (i.e. the controls wrapper).

Finally, we set up a drag listener to move the full-sized content according to how far the user has dragged the control. For this, we negatively positioned the content to the left by the drag amount multiplied by the ratio of the controls to the content.

Custom Cursors

The draggable content is working, but we still have room for improvement.

First let’s add some more styling to the control box to make it more interactive. jQuery UI’s draggable attaches two class names that we can use for this: ui-draggable and ui-draggable-dragging.

01 #drag-controls.ui-draggable {
02 cursor: -moz-grab !important;
03 cursor: -webkit-grab !important;
04 cursor: e-resize;
05 }
07 #drag-controls.ui-draggable-dragging {
08 cursor: -moz-grabbing !important;
09 cursor: -webkit-grabbing !important;
10 border-color: yellow;
11 }

In addition to applying a new border color to the active controls, this snippet also attaches a number of cursor properties, which use proprietary UI cursors available in Firefox and Safari, with a back-up for IE.

Because of the implementation of the cursor property, we had to “bootstrap” this together using !important. This ensures that the proprietary cursors are used if available, while allowing the default cursor to overwrite them in IE. Unfortunately, Chrome does not currently support -webkit-grab, so we leave it out of this implementation. If you’d prefer to use the back-up e-resize cursor in both Chrome and Safari, just remove the -webkit-grab and -webkit-grabbing properties.

Parallax Effect

Let’s make the sliding animation more three-dimensional by adding a two-layer parallax effect. To do so, we simply add a background to our full-sized content area and animate it at a slower rate.

Add the mark-up first:

01 <div id="full-sized-area">
02 <div id="full-sized-background">
03 Your background here
04 </div>
06 <div id="full-sized-content">
07 Your content here
08 </div>
09 </div>
11 <div id="drag-controls-area">
12 <div id="drag-controls"></div>
13 </div>

And then some basic styling:

1 #full-sized-background {
2 position: absolute;
3 top: 0;
4 left: 0;
5 }

Here, we use absolute positioning to lock the background in place. Note that we did not need to attach a z-index, because we placed the background element before the content area in the mark-up.

Finally, let’s add the background animation to our drag event:

01 $fullBackground = $('#full-sized-background');
03 $controls.draggable({
04 axis : 'x', // confine dragging to the x-axis
05 containment : 'parent',
06 drag : function(ev, ui) {
07 // move the full sized content
08 var newContentPosition = -1 * ui.position.left / scaleRatio;
09 $fullContent.css('left', newContentPosition);
11 // move the background
12 $fullBackground.css('left', newContentPosition * .4);
13 }
14 });

Here, we simply used the new position that we calculated for the main content and applied 40% of that change to the background. Adjust this value to change the speed of the parallax.

3. Subtle Hover Effects

Veerle in Five Useful CSS/jQuery Coding Techniques For More Dynamic Websites

Veerle’s blog uses subtle transitions to create a natural feel for mouse interactions. These can be easily accomplished using CSS3’s transition property (and a jQuery back-up for unsupported browsers).

First, let’s attach some CSS with the class subtle to all elements:

1 .subtle {
2 background-color: #78776C;
3 color: #BBBBAD;
4 }
6 .subtle:hover, .subtle:focus {
7 background-color: #F6F7ED;
8 color: #51514A;
9 }

Here, we’ve styled these elements with a background and text color and included a hover state using the pseudo-class :hover. Additionally, we included the :focus pseudo-class for active input and text-area elements.

This CSS causes the style to change immediately on hover, but we can apply a smoother transition using CSS3:

01 .subtle {
02 -webkit-transition: background-color 500ms ease-in; /* Saf3.2+, Chrome */
03 -moz-transition: background-color 500ms ease-in; /* FF3.7+ */
04 -o-transition: background-color 500ms ease-in; /* Opera 10.5+ */
05 transition: background-color 500ms ease-in; /* futureproofing */
06 background-color: #78776C;
07 color: #BBBBAD;
08 }
10 .subtle:hover, .subtle:focus {
11 background-color: #F6F7ED;
12 color: #51514A;
13 }

Here, we’ve attached a CSS3 transition that works in all modern browsers except IE. The transition property consists of three different values. The first is the CSS property to animate, and the second is the duration of the animation—in our case, background-color and 500 milliseconds, respectively. The third value allows us to specify an easing function, such as ease-in or linear.

jQuery Back-Up

Our subtle transitions now work across a variety of browsers, but let’s include support for all users by leveraging a jQuery back-up technique.

First we’ll need to detect whether the user’s browser supports transition:

1 // make sure to execute this on page load
2 $(function() {
3 // determine if the browser supports transition
4 var thisStyle =,
5 supportsTransition = thisStyle.WebkitTransition !== undefined ||
6 thisStyle.MozTransition !== undefined ||
7 thisStyle.OTransition !== undefined ||
8 thisStyle.transition !== undefined;
9 });

Here, we check whether the body element can use any of the browser-specific transition properties that we defined above.

If the browser doesn’t support transition, we can apply the animation using jQuery. However, jQuery’s animate() function does not natively support color-based animations. To accommodate our background-color animation, we’ll have to include a small chunk of jQuery UI: the effects core.

After including jQuery UI, we’ll need to attach the animation to the hover and focus event listeners:

01 // make sure to execute this on page load
02 $(function() {
03 // determine if the browser supports transition
04 var thisStyle =,
05 supportsTransition = thisStyle.WebkitTransition !== undefined ||
06 thisStyle.MozTransition !== undefined ||
07 thisStyle.OTransition !== undefined ||
08 thisStyle.transition !== undefined;
10 // assign jQuery transition if the browser doesn't support
11 if ( ! supportsTransition ) {
12 var defaultCSS = {
13 backgroundColor: '#78776C'
14 },
15 hoverCSS = {
16 backgroundColor: '#F6F7ED'
17 };
19 // loop through each button
20 $('.subtle').each(function() {
21 var $subtle = $(this);
23 // bind an event listener for mouseover and focus
24 $subtle.bind('mouseenter focus', function() {
25 $subtle.animate(hoverCSS, 500, 'swing' );
26 });
28 // bind the reverse for mouseout and blur
29 $subtle.bind('mouseleave blur', function(ev) {
30 if ( ev.type == 'mouseleave' && == document.activeElement ) return false;
32 $subtle.animate(defaultCSS, 500, 'swing' );
33 });
34 });
35 }
36 });

Here, we recreated the transition using jQuery’s animate(). Notice how we used values that are to the CSS3 transition—500 specifies 500 milliseconds, and swing specifies an easing method that is close to ease-in.

While the mouse-over and focus event is fairly straightforward, notice the difference in the mouse-out and blur event. We added some code to end the function if the element is in focus. This retains the active state even if the user moves their mouse. jQuery’s is() method does not support the :focus pseudo-class, so we have to rely on DOM’s document.activeElement.

4. Comment Count Bars

Most-commented in Five Useful CSS/jQuery Coding Techniques For More Dynamic Websites

IT Expert Voice uses a nice method for displaying the “Most commented” posts in its sidebar. Let’s recreate this using WordPress and a bit of CSS and jQuery (non-WordPress users can skip the first section).

Pulling Posts With WordPress

Let’s start by pulling in the top-five most-commented posts:

1 <?php $most_commented = new WP_Query('orderby=comment_count&posts_per_page=5'); ?>

Here, we used WP_Query and a custom variable name so as not to disrupt any other post loops on the page.

Next, let’s loop through the posts we’ve selected, outputting each as a list item:

01 <ul id="most-commented">
03 <?php $most_commented = new WP_Query('orderby=comment_count&posts_per_page=5'); ?>
04 <?php while ($most_commented->have_posts()) : $most_commented->the_post(); ?>
06 <li>
07 <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
09 <span class="comment-bar"><span class="comment-count"><?php comments_number('0','1','%'); ?></span></span>
10 </li>
12 <?php endwhile; ?>
14 </ul>

Here, we used a while() loop to run through each post. First, we output a link to the post using the_permalink() and the_title(), and then we output the comment count using comments_number() and some additional mark-up for styling.

Basic CSS Styling

Let’s style the basic layout of the comments list using CSS:

1 #most-commented li {
2 list-style: none;
3 }
5 #most-commented a {
6 display: block;
7 }

We’ve removed any list styling and defined the links as a block element so that they stay separate from our comment bar visualizations.

Let’s set up some base styles for the comment bar and comment count:

01 #most-commented .comment-bar {
02 display: inline-block;
03 position: relative;
04 height: 30px;
05 width: 0;
06 margin: 5px 0;
07 padding-left: 20px;
08 background-color: #999;
09 }
11 #most-commented .comment-count {
12 display: inline-block;
13 position: absolute;
14 right: -20px;
15 top: -5px;
16 width: 34px;
17 height: 34px;
18 border-width: 3px;
19 border-style: solid;
20 border-color: #FFF;
21 -moz-border-radius: 20px;
22 -webkit-border-radius: 20px;
23 border-radius: 20px;
24 text-align: center;
25 line-height: 34px;
26 background-color: #6CAC1F;
27 font-size: 13px;
28 font-weight: bold;
29 color: #FFF;
30 }

Most of this styling is arbitrary, so feel free to attach a background image or otherwise tweak it to fit your theme. The main thing is to align the comment count to the right of the comment bar so that we can adjust the width of the bar at will.

Pay attention to the total width of the comment count, in our case 40px (34px wide plus 3px for the left and right borders). We’re using half of that value to position the comment count: 20px of negative positioning so that the count hangs on the right, and 20px of left padding so that the comment bar reaches the center of the comment count.

Tying It All Together With jQuery

Finally, let’s use jQuery to set the widths of the individual bars. We’ll start by looping through the comments after the page loads:

1 $(function() {
2 $('#most-commented li').each(function(i) {
3 var $this = $(this);
4 var thisCount = ~~$this.find('.comment-count').text();
5 });
6 });

We loop through all of the <li> elements, pulling out the comment count from the mark-up. Notice that we’ve used the primitive data type ~~ to convert the text to an integer. This is significantly faster than alternatives such as parseInt().

Let’s set up some key variables in the first iteration of our loop:

01 $(function() {
02 // define global variables
03 var maxWidth, maxCount;
05 $('#most-commented li').each(function(i) {
06 var $this = $(this);
07 var thisCount = ~~$this.find('.comment-count').text();
09 // set up some variables if the first iteration
10 if ( i == 0 ) {
11 maxWidth = $this.width() - 40;
12 maxCount = thisCount;
13 }
14 });
15 });

Here, we started by defining variables outside of the each() loop. This allows us to use these values in every iteration.

Next, we subtracted 40 pixels from the width of the list item to define a maximum width for the comment bar. The 40 pixels compensate for the left-padding and negative position that we applied above.

We also set maxCount to the first value. Because we initially pulled the posts according to their number of comments, we can be sure that the first item will have the highest count.

Finally, let’s calculate the width of each bar and animate the transition:

01 $(function() {
02 // define global variables
03 var maxWidth, maxCount;
05 $('#most-commented li').each(function(i) {
06 var $this = $(this);
07 var thisCount = ~~$this.find('.comment-count').text();
09 // set up some variables if the first iteration
10 if ( i == 0 ) {
11 maxWidth = $this.width() - 40;
12 maxCount = thisCount;
13 }
15 // calculate the width based on the count ratio
16 var thisWidth = (thisCount / maxCount) * maxWidth;
18 // apply the width to the bar
19 $this.find('.comment-bar').animate({
20 width : thisWidth
21 }, 200, 'swing');
22 });
23 });

If you’d rather style the elements without any animation, simply replace the animate() with a static css().

5. Full-Page Slider

Wine-jax in Five Useful CSS/jQuery Coding Techniques For More Dynamic Websites

Sliding animation is an interactive way to show related content. But JAX Vineyards takes the standard sliding gallery to the next level by animating across the entire page. Let’s create a similar effect using jQuery.

Mark-Up and CSS

Start by adding the mark-up:

01 <div id="full-slider-wrapper">
02 <div id="full-slider">
04 <div class="slide-panel active">
05 Panel 1 content here
06 </div>
08 <div class="slide-panel">
09 Panel 2 content here
10 </div>
12 <div class="slide-panel">
13 Panel 3 content here
14 </div>
15 </div>
16 </div>

We set up the basic mark-up and wrappers that we need for the animation. Make sure that the full-slider-wrapper is not contained in any element that is narrower than the browser window—we’ll need the full width of the browser to pull off the effect.

Now, let’s add some basic CSS to handle overflow and to position the panels:

01 html {
02 min-width: 800px;
03 }
05 #full-slider-wrapper {
06 overflow: hidden;
07 }
09 #full-slider {
10 position: relative;
11 width: 800px;
12 height: 600px;
13 margin: 0 auto;
14 }
16 #full-slider .slide-panel {
17 position: absolute;
18 top: 0;
19 left: 0;
20 width: 800px;
21 height: 600px;
22 visibility: hidden;
23 }
25 #full-slider {
26 visibility: visible;
27 }

We defined absolute positioning and set up some arbitrary dimensions for the panels and wrapper. Feel free to tweak these dimensions to your content.

We also attached overflow: hidden to our wrapper element, which will prevent scroll bars from appearing when we animate the panels. Because we hid the overflow, we also had to assign a min-width to the html document. This ensures that the content will get scroll bars if the browser window is too small.

Finally, we used the active class that we established in the mark-up to show the first panel.

jQuery Animation

Let’s build the interaction using jQuery. We’ll start by defining some variables and then create a function to handle the sliding animation in both directions:

01 $(function() {
02 var $slider = $('#full-slider');
03 var $sliderPanels = $slider.children('.slide-panel');
05 function slidePanel( newPanel, direction ) {
06 // define the offset of the slider obj, vis a vis the document
07 var offsetLeft = $slider.offset().left;
09 // offset required to hide the content off to the left / right
10 var hideLeft = -1 * ( offsetLeft + $slider.width() );
11 var hideRight = $(window).width() - offsetLeft;
13 // change the current / next positions based on the direction of the animation
14 if ( direction == 'left' ) {
15 currPos = hideLeft;
16 nextPos = hideRight;
17 }
18 else {
19 currPos = hideRight;
20 nextPos = hideLeft;
21 }
23 // slide out the current panel, then remove the active class
24 $slider.children('').animate({
25 left: currPos
26 }, 500, function() {
27 $(this).removeClass('active');
28 });
30 // slide in the next panel after adding the active class
31 $( $sliderPanels[newPanel] ).css('left', nextPos).addClass('active').animate({
32 left: 0
33 }, 500 );
34 }
35 });

Here our slidePanel() function accepts two arguments: the index of the panel that we want to slide into view, and the direction of the slide (i.e. left or right).

Although this function looks complicated, the concepts are fairly simple. We determined the amount of offset necessary to hide the panels on the left and right sides. To calculate these values, we used jQuery’s offset() and the slider and window widths. These offsets represent the left position values needed to hide the content on either side.

Next, we have a switch based on the direction of the animation, which uses the two values we defined previously.

Finally, we trigger the animation using jQuery’s animate(). We slide the active panel out of view and then remove the active class once the animation completes. Then we set the new panel’s left position off the screen, attach the active class to make it visible and slide it into place.

Building the Controls

Our function now handles the animation, but we still have to build controls to leverage it.

Append navigation elements to the slider object that we defined previously:

1 var $navWrap = $('<div id="full-slider-nav"></div>').appendTo( $slider );
2 var $navLeft = $('<div id="full-slider-nav-left"></div>').appendTo( $navWrap );
3 var $navRight = $('<div id="full-slider-nav-right"></div>').appendTo( $navWrap );

We could have included this navigation in the initial mark-up, but we’re appending it with JavaScript for two reasons: it ensures that the navigation won’t appear until the JavaScript is loaded, and it keeps the navigation from being displayed on the off chance that JavaScript isn’t enabled.

Let’s style the navigation:

01 #full-slider-nav {
02 position: absolute;
03 top: 0;
04 right: 0;
05 }
07 #full-slider-nav-left, #full-slider-nav-right {
08 display: inline-block;
09 height: 0;
10 width: 0;
11 margin-left: 15px;
12 border: 20px solid transparent;
13 cursor: pointer;
14 }
16 #full-slider-nav-left {
17 border-right-color: #BBB;
18 }
20 #full-slider-nav-left:hover {
21 border-right-color: #999;
22 }
24 #full-slider-nav-right {
25 border-left-color: #BBB;
26 }
28 #full-slider-nav-right:hover {
29 border-left-color: #999;
30 }

Here we absolute position the navigation to the top right. We also use a CSS triangle trick to quickly style the controls.

Let’s attach our new slider navigation to the slidePanel() function that we defined previously:

01 var $navWrap = $('<div id="full-slider-nav"></div>').appendTo( $slider );
02 var $navLeft = $('<div id="full-slider-nav-left"></div>').appendTo( $navWrap );
03 var $navRight = $('<div id="full-slider-nav-right"></div>').appendTo( $navWrap );
05 var currPanel = 0;
07 $ {
08 currPanel--;
10 // check if the new panel value is too small
11 if ( currPanel < 0 ) currPanel = $sliderPanels.length - 1;
13 slidePanel(currPanel, 'right');
14 });
16 $ {
17 currPanel++;
19 // check if the new panel value is too big
20 if ( currPanel >= $sliderPanels.length ) currPanel = 0;
22 slidePanel(currPanel, 'left');
23 });

This snippet assigns click events to the left and right navigation. In each, we change the value of currPanel according to the direction. If this new value falls outside of the available panels, we loop to the other end of our set. Finally, we trigger the slidePanel() function with the new panel and appropriate direction.

In our example, we built controls only for left and right navigation, but you could easily tweak this to have buttons for each panel. Simply pass the correct panel index to slidePanel.

Let’s bring all the jQuery code together:

01 $(function() {
02 function slidePanel( newPanel, direction ) {
03 // define the offset of the slider obj, vis a vis the document
04 var offsetLeft = $slider.offset().left;
06 // offset required to hide the content off to the left / right
07 var hideLeft = -1 * ( offsetLeft + $slider.width() );
08 var hideRight = $(window).width() - offsetLeft;
10 // change the current / next positions based on the direction of the animation
11 if ( direction == 'left' ) {
12 currPos = hideLeft;
13 nextPos = hideRight;
14 }
15 else {
16 currPos = hideRight;
17 nextPos = hideLeft;
18 }
20 // slide out the current panel, then remove the active class
21 $slider.children('').animate({
22 left: currPos
23 }, 500, function() {
24 $(this).removeClass('active');
25 });
27 // slide in the next panel after adding the active class
28 $( $sliderPanels[newPanel] ).css('left', nextPos).addClass('active').animate({
29 left: 0
30 }, 500 );
31 }
33 var $slider = $('#full-slider');
34 var $sliderPanels = $slider.children('.slide-panel');
36 var $navWrap = $('<div id="full-slider-nav"></div>').appendTo( $slider );
37 var $navLeft = $('<div id="full-slider-nav-left"></div>').appendTo( $navWrap );
38 var $navRight = $('<div id="full-slider-nav-right"></div>').appendTo( $navWrap );
40 var currPanel = 0;
42 $ {
43 currPanel--;
45 // check if the new panel value is too small
46 if ( currPanel < 0 ) currPanel = $sliderPanels.length - 1;
48 slidePanel(currPanel, 'right');
49 });
51 $ {
52 currPanel++;
54 // check if the new panel value is too big
55 if ( currPanel >= $sliderPanels.length ) currPanel = 0;
57 slidePanel(currPanel, 'left');
58 });
59 });

Final Thoughts

In this post we walked through a variety of methods for adding dynamic functionality to your websites. These techniques can be easily adapted to work with almost any site. The majority of these techniques rely on jQuery to provide interaction, but there are plenty of other approaches, both with and without jQuery. Please post any alternate solutions in the comments below, or fork the example files on github.

Furthermore, these five methods represent only a small portion of interactive techniques. Please post any links to other dynamic techniques and functionality in the comments below.

Form validation with jQuery from scratch

The HTML form

There’s a pretty diverse opinion on how this should be done exactly, but we’ll make the code flexible enough to handle different markup styles.

        <legend>Legend Name</legend>
            <label for="name">Name</label>
            <input type="text" id="name" name="name">

This is how I markup my forms. Trying to keep it as simple and semantic as possible, but adding the div to make styling easier.

Specifying input validation

In HTML4 there is no obvious way attach validation rules to an input. A few developers have been somewhat orthodox and added their own “validation” attribute.

<input type="text" id="name" name="name" validation=”required email”>

This is not valid HTML, but it works in all browsers, and maybe it’s better than using a valid attribute for the wrong reasons. It’s up to you, but this is how I do it.

The validation object

The base validation object contains a set of methods and properties that only needs be stored in one place, but can be accessed globally. In object oriented terminology this is commonly referred to as a Singleton.

// Wrap code in an self-executing anonymous function and
// pass jQuery into it so we can use the "$" shortcut without
// causing potential conflicts with already existing functions.
(function($) {

    var validation = function() {

        var rules = {  // Private object

            email : {
               check: function(value) {

                   if(value) {
                       return testPattern(value,".+@.+\..+");
                   return true;
               msg : "Enter a valid e-mail address."
            required : {

               check: function(value) {

                   if(value) {
                       return true;
                   else {
                       return false;
               msg : "This field is required."
        var testPattern = function(value, pattern) {   // Private Method

            var regExp = new RegExp("^"+pattern+"$","");
            return regExp.test(value);
        return { // Public methods

            addRule : function(name, rule) {

                rules[name] = rule;
            getRule : function(name) {

                return rules[name];
    //A new instance of our object in the jQuery namespace.
    $.validation = new validation();
// Again, we're passing jQuery into the function
// so we can use $ without potential conflicts. 

The object contains a set of rules, each with a function and a message. There’s also a function called “testPattern”. Being defined with the var keyword makes them private and inaccessible outside the object itself.

NOTE: I’ve simplified the regular expressions above to make the example readable. I suggest you take a look at the expressions from the official jQuery valide plugin for the real deal.

Adding the object to the jQuery $ namespace is useful because now we can access it like any other jQuery object, hence, it’ll be helpful later on in our plugin code.

Public methods

Instead of hard coding lots of rules, we keep it down to a minimum. We defined a method called “addRule” and made it public by wrapping it in a return statement. The concept of returning methods and properties to make them public is commonly referred to as the module pattern.

Adding additional validation rules

People can now use our method to quickly add new custom validation rules without having to modify our code.

    check: function(value) {
        if(value != "test") {
            return false;
        return true;
    msg : "Must equal to the word test."

We’ve now added a custom validation rule called “test”, maybe not so useful, but consider the next example. We add a rule to check whether a username is taken or not, with an imaginary AJAX request.

$.validation.addRule("xhr-test", {
    check: function(value) {
        $.get("/url-to-username-check", { username: value }, function(data) {
            if(data.isValid) {
                return true;
            return false;
    msg : "Username already exists."
Obviously, you’d want to improve the above
example to handle possible AJAX failures.

Some people will by now probably point out that the addRule method is essentially the same as making the object public and letting people add stuff to it themselves. Yes, that’s true, but this a VERY simple abstraction. Should the code get any more advanced an abstraction like this could be helpful for anyone using your code.

Take a look inside

Lets take a look at our object in the firebug console.


It should simply print out “object”. If you click it you’ll see the public methods we added earlier on. Let’s see what the getRule method produces.


As you’ll see, it returns the rule we added earlier. In OOP terminology we’ve now implemented getters and setters. Instead of allowing direct access to an objects private properties. It’s better to have public methods that make these changes. It produces a cleaner API to the end user and it gives us more flexibility in case something else needs to run when modifying a property.

But someone told me the module pattern sucks…

Although I prefer this style of coding, it should be said that some developers neglect the idea of hiding properties and methods (a.k.a data encapsulation) in JavaScript. I think there are some very legitimate arguments linked to that statement. I leave it up to you to make up your own mind, nevertheless it’s good to have knowledge of different design patterns even if you don’t use them.

The form object

The form object will represent an instance of a form in the DOM.

var Form = function(form) {

    var fields = [];
    // Get all input elements in form
    $(form[0].elements).each(function() {
        var field = $(this);
        // We're only interested in fields with a validation attribute
        if(field.attr('validation') !== undefined) {
            fields.push(new Field(field));
    this.fields = fields;

A form has a number of fields belonging to it. We iterate over all the inputs and textareas that has a validation attribute using the jQuery each method. For each field there is, we create a new instance of the Field object which looks like this:

var Field = function(field) {
    this.field = field;
    this.valid = false;

We’ve defined some properties using the this keyword which refers to the object itself. We can now create any number of “form” instances with the new keyword.

var comment_form = new Form($("#comment_form"));
//another instance
var contact_form = new Form($("#contact_form"));
//Take a look inside the object

Providing your forms actually contain some fields with a validation attribute, you should see some interesting results when printing the object in the firebug console.

The JavaScript prototype object

This may seem like a tricky concept at first, but once you can wrap your head around prototypal inheritance, it’s a really powerful and useful feature of the JavaScript language.

The problem

We have a large number of instances of the Field object, all of which we need to add some methods to. At first it may seem like a perfectly good idea to do the following:

Field.validate = function() {}

But this essentially means that if we have 30 fields instances, we will have 30 instances of the validate function, which is really a waste, since they all do the same thing.

The solution

Adding the validate method to the prototype object of Field will make all instances of Field inherit the validate method, but the validate method only exists in one place, so any changes to it will be reflected upon all instances of the Field object.

field.prototype.validate = function() {}

This feature should be used with care, especially when used on native javascript objects, before you fiddle around with it to much I recommend you read up further on the subject.

The Field validation methods

These are thetwo methods attached to the Field prototype object.

Field.prototype = {
    // Method used to attach different type of events to
    // the field object.
    attach : function(event) {

        var obj = this;
        if(event == "change") {
            obj.field.bind("change",function() {
                return obj.validate();
        if(event == "keyup") {
            obj.field.bind("keyup",function(e) {
                return obj.validate();

    // Method that runs validation on a field
    validate : function() {

        // Create an internal reference to the Field object.
        var obj = this,
            // The actual input, textarea in the object
            field = obj.field,
            errorClass = "errorlist",
            errorlist = $(document.createElement("ul")).addClass(errorClass),
            // A field can have multiple values to the validation
            // attribute, seprated by spaces.
            types = field.attr("validation").split(" "),
            container = field.parent(),
            errors = []; 

        // If there is an errorlist already present
        // remove it before performing additional validation".errorlist").remove();

        // Iterate over validation types
        for (var type in types) {

            // Get the rule from our Validation object.
            var rule = $.Validation.getRule(types[type]);
            if(!rule.check(field.val())) {

        // If there is one ore more errors
        if(errors.length) {

            // Remove existing event handler
            // Attach the keyup event to the field because now
            // we want to let the user know as soon as she has
            // corrected the error

            // Empty existing errors, if any.
            for(error in errors) {

                errorlist.append("<li>"+ errors[error] +"</li>");
            obj.valid = false;
        // No errors
        else {
            obj.valid = true;

As a last step, we’re going to edit the Field object we defined earlier:

var Field = function(field) {

    this.field = field;
    this.valid = false;
    this.attach("change"); // add this line.

Now each field will validate upon the “change” event.

Finishing the Form Object

Now our Field object is pretty much complete, let’s add a few more features to the Form object before moving on to the actual jQuery plugin implementation.

Form.prototype = {
    validate : function() {

        for(field in this.fields) {

    isValid : function() {

        for(field in this.fields) {

            if(!this.fields[field].valid) {

                // Focus the first field that contains
                // an error to let user fix it.

                // As soon as one field is invalid
                // we can return false right away.
                return false;
        return true;

The jQuery plugin methods

We’re going to use the jQuery extend method to make our plugin accessible as methods on any jQuery object.

$.extend($.fn, {

    validation : function() {

        var validator = new Form($(this));
        $.data($(this)[0], 'validator', validator);

        $(this).bind("submit", function(e) {

            if(!validator.isValid()) {

    validate : function() {

        var validator = $.data($(this)[0], 'validator');
        return validator.isValid();

The validation method is what we use to create a new validation instance associated to a form. You can see that we’re creating a new form instance and also binding the a submit event handler to run the validation upon form submission.

The jQuery $.data method

This is pretty nifty feature and allows us to store data assoicated to a jQuery object. In this case, we are storing an instance of the form object inside the object passed into the plugin. In the validate method, that we use to validate the form at anytime, we can now call the already existing form instance, instead of creating a new one.


Based on the plugin that we’ve now built, here’s some usage examples.

$(function(){ // jQuery DOM ready function.

    var myForm = $("#my_form");


    // We can check if the form is valid on
    // demand, using our validate function.
    $("#test").click(function() {

        if(!myForm.validate()) {

            alert("oh noes.. error!");

30 Tutorials Combining Both WordPress and jQuery

Take the most popular CMS, WordPress, and then take the easiest and most versatile of Javscript libraries, jQuery, and you have a match made in heaven. Implementing jQuery within WordPress is a lot easier than you would think, all you need is a little support from the huge WP community and a little patience, and you are good to go. Below you will find 30 Tutorials Combining both WordPress and jQuery.

Including jQuery in WordPress (The Right Way)

When you download jQuery, put it on your server and link to it from your header.php file in the <head> section, this can cause you problems. Some plugins use the jQuery library, and they are going to load it as well and on top of that already has the jQuery library included. This can cause problems.
In this tutorial you will learn how to load up jQuery in your theme the smart (and intended) way, avoiding conflicts.

Display a Random Post (with AJAX Refresh)

In this tutorial you will learn how to display a random post with Ajax refresh, and you will be surprised at how easy this is to do. You are going to leverage some serious smartness from both WordPress and from the JavaScript library jQuery.

Design An Elegant Featured Content Slider for WordPress

In this tutorial, you’ll create an elegant featured content slider for WordPress based on The Coda Slider, a neat device used by Panic Software to display information about their “Coda” product on their website. This effect is beautiful, flexible, and often emulated.

Create an Attractive jQuery Menu with Fadein and Fadeout Effect

In this tutorial you will create a jQuery menu using the Fadein and Fadeout effect. To develop the menu it requires a lot of CSS works, so roll up your sleeves.

How to Highlight Search Terms with jQuery

A nice way to spice up your WordPress search page is to highlight search terms within your search results. In this tutorial you will learn to highlight both title and post content.

WordPress Featured Post Slideshow

In this tut you’ll be learning how to create a featured and “latest posts” section within WordPress, and animate it with jQuery. You will be using the jQuery Cycle plugin built for slideshows. To make it work you give it an element and it turns every child of that element into a slide.

Implement a Nice & Clean jQuery Sliding Panel in WordPress

In this tutorial, you will learn how to create a smooth sliding login/signup panel for your WordPress site using jQuery.

Build a Basic Newspaper style layout with WordPress and jQuery

Grid and Magazine templates are becoming more and more popular in WordPress development, so, in this tutorial you will use jQuery to create a grid layout with size-degrading headers.

Build the ANidea Theme Switcher using jQuery

This tutorial will teach you how to create the cool theme switcher that is used on the ANidea web site. In the tutorial, you’ll cover the client side of Theme Switcher, which consists of the HTML, CSS and JavaScript (jQuery).

How To Create Tabs Using jQuery

This tutorial is primarily for WordPress, but can easily be ported anywhere else. You will be creating a tabs section within the sidebar, a popular and useful feature in WordPress themes.

Use jQuery to Jazz Up Your List of Latest Posts

A lot of blogs display a list of their most recent or popular posts in their sidebar, more often than not just showing the title of each one. But how can you give your reader an idea of what that post is about by using the excerpt, without taking up too much room? Using a little jQuery, you can.

Create a jQuery Carousel with WordPress Posts

This tutorial will give you a quick run down of how to easily add a simple and easily customizable carousel with WordPress posts from a specified category, using the jQuery plugin jFlow.

Adding Form Validation to WordPress Comments using jQuery

When it comes to simpler user experience, having your form validation happen instantly on the same page is a lot cleaner than reloading pages and possibly losing some form content. In this tutorial you’ll be shown how to use jQuery to do some instant checking on a comment form.

Using jQuery to liven up your WordPress Login

Using the jQuery principal “less is more…”, in this tutorial you will learn a quick method of simplifying the clients login process using a jQuery lightbox.



Blog Posts

Privacy Policy | Terms & Conditions Copyright 2011 , Techliance..! Techliance & Techliance logo are trademarks of Techliance LLC. Other products, logos, and company names on Techliance website may be trademarks or trade names of their respective owners.

Join Us On