Category Archives:

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();
05
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();
05
06 // remove any old highlighted terms
07 $('body').removeHighlight();
08
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 }
21
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>
6
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 }
07
08 #full-sized-content {
09 position: absolute;
10 top: 0;
11 left: 0;
12 }
13
14 #drag-controls-area {
15 position: relative;
16 width: 300px;
17 height: 50px;
18 }
19
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);
04
05 // find what portion of the content is displayed
06 var contentRatio = $fullArea.width() / $fullContent.width();
07
08 // scale the controls box
09 var $controlsArea = $('#drag-controls-area');
10 var $controls = $('#drag-controls', $controlsArea);
11
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);
04
05 // find what portion of the content is displayed
06 var contentRatio = $fullArea.width() / $fullContent.width();
07
08 // scale the controls box
09 var $controlsArea = $('#drag-controls-area');
10 var $controls = $('#drag-controls', $controlsArea);
11
12 $controls.css('width', $controlsArea.width() * contentRatio);
13
14 // determine the scale difference between the controls and content
15 var scaleRatio = $controlsArea.width() / $fullContent.width();
16
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 }
06
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>
05
06 <div id="full-sized-content">
07 Your content here
08 </div>
09 </div>
10
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');
02
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);
10
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 }
5
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 }
09
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 = document.body.style,
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 = document.body.style,
05 supportsTransition = thisStyle.WebkitTransition !== undefined ||
06 thisStyle.MozTransition !== undefined ||
07 thisStyle.OTransition !== undefined ||
08 thisStyle.transition !== undefined;
09
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 };
18
19 // loop through each button
20 $('.subtle').each(function() {
21 var $subtle = $(this);
22
23 // bind an event listener for mouseover and focus
24 $subtle.bind('mouseenter focus', function() {
25 $subtle.animate(hoverCSS, 500, 'swing' );
26 });
27
28 // bind the reverse for mouseout and blur
29 $subtle.bind('mouseleave blur', function(ev) {
30 if ( ev.type == 'mouseleave' && ev.target == document.activeElement ) return false;
31
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">
02
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(); ?>
05
06 <li>
07 <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
08
09 <span class="comment-bar"><span class="comment-count"><?php comments_number('0','1','%'); ?></span></span>
10 </li>
11
12 <?php endwhile; ?>
13
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 }
4
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 }
10
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;
04
05 $('#most-commented li').each(function(i) {
06 var $this = $(this);
07 var thisCount = ~~$this.find('.comment-count').text();
08
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;
04
05 $('#most-commented li').each(function(i) {
06 var $this = $(this);
07 var thisCount = ~~$this.find('.comment-count').text();
08
09 // set up some variables if the first iteration
10 if ( i == 0 ) {
11 maxWidth = $this.width() - 40;
12 maxCount = thisCount;
13 }
14
15 // calculate the width based on the count ratio
16 var thisWidth = (thisCount / maxCount) * maxWidth;
17
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">
03
04 <div class="slide-panel active">
05 Panel 1 content here
06 </div>
07
08 <div class="slide-panel">
09 Panel 2 content here
10 </div>
11
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 }
04
05 #full-slider-wrapper {
06 overflow: hidden;
07 }
08
09 #full-slider {
10 position: relative;
11 width: 800px;
12 height: 600px;
13 margin: 0 auto;
14 }
15
16 #full-slider .slide-panel {
17 position: absolute;
18 top: 0;
19 left: 0;
20 width: 800px;
21 height: 600px;
22 visibility: hidden;
23 }
24
25 #full-slider .slide-panel.active {
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');
04
05 function slidePanel( newPanel, direction ) {
06 // define the offset of the slider obj, vis a vis the document
07 var offsetLeft = $slider.offset().left;
08
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;
12
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 }
22
23 // slide out the current panel, then remove the active class
24 $slider.children('.slide-panel.active').animate({
25 left: currPos
26 }, 500, function() {
27 $(this).removeClass('active');
28 });
29
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 }
06
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 }
15
16 #full-slider-nav-left {
17 border-right-color: #BBB;
18 }
19
20 #full-slider-nav-left:hover {
21 border-right-color: #999;
22 }
23
24 #full-slider-nav-right {
25 border-left-color: #BBB;
26 }
27
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 );
04
05 var currPanel = 0;
06
07 $navLeft.click(function() {
08 currPanel--;
09
10 // check if the new panel value is too small
11 if ( currPanel < 0 ) currPanel = $sliderPanels.length - 1;
12
13 slidePanel(currPanel, 'right');
14 });
15
16 $navRight.click(function() {
17 currPanel++;
18
19 // check if the new panel value is too big
20 if ( currPanel >= $sliderPanels.length ) currPanel = 0;
21
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;
05
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;
09
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 }
19
20 // slide out the current panel, then remove the active class
21 $slider.children('.slide-panel.active').animate({
22 left: currPos
23 }, 500, function() {
24 $(this).removeClass('active');
25 });
26
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 }
32
33 var $slider = $('#full-slider');
34 var $sliderPanels = $slider.children('.slide-panel');
35
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 );
39
40 var currPanel = 0;
41
42 $navLeft.click(function() {
43 currPanel--;
44
45 // check if the new panel value is too small
46 if ( currPanel < 0 ) currPanel = $sliderPanels.length - 1;
47
48 slidePanel(currPanel, 'right');
49 });
50
51 $navRight.click(function() {
52 currPanel++;
53
54 // check if the new panel value is too big
55 if ( currPanel >= $sliderPanels.length ) currPanel = 0;
56
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.

 

 

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