CSSKarma

display your <style>

designing the web since 2002

Posts Tagged ‘jquery’

« Older Entries |

Sliding Labels v2 – Patch

Tuesday, February 2nd, 2010

banner

Last week I wrote an article about sliding form labels that got quite a bit of attention. Many of the commenters brought up a couple good points/bug in the Sliding Label code that I wanted to address and provide a patch for:

  • The sliding label was barfing out in Safari when auto-fill was active
  • The default scripting didn’t work on textareas

I sat down yesterday and wrote a patch/new version of sliding labels which I think addresses these two problems.

View the Demo

The new jQuery

$(function(){
$('form#info .slider label').each(function(){
	var labelColor = '#999';
	var restingPosition = '5px';

	// style the label with JS for progressive enhancement
	$(this).css({
		'color' : labelColor,
		 	'position' : 'absolute',
	 		'top' : '6px',
			'left' : restingPosition,
			'display' : 'inline',
    		        'z-index' : '99'
	});

	var inputval = $(this).next().val();

	// grab the label width, then add 5 pixels to it
	var labelwidth = $(this).width();
	var labelmove = labelwidth + 5 +'px';

	// onload, check if a field is filled out, if so, move the label out of the way
	if(inputval !== ''){
		$(this).stop().animate({ 'left':'-'+labelmove }, 1);
	}    	

	// if the input is empty on focus move the label to the left
	// if it's empty on blur, move it back
	$('input, textarea').focus(function(){
		var label = $(this).prev('label');
		var width = $(label).width();
		var adjust = width + 5 + 'px';
		var value = $(this).val();

		if(value == ''){
			label.stop().animate({ 'left':'-'+adjust }, 'fast');
		} else {
			label.css({ 'left':'-'+adjust });
		}
	}).blur(function(){
		var label = $(this).prev('label');
		var value = $(this).val();

		if(value == ''){
			label.stop().animate({ 'left':restingPosition }, 'fast');
		}	

	});
}); // End "each" statement
}); // End loaded jQuery

Textarea HTML

The HTML for the textarea follows the same convention as the rest of the inputs, in only needing a wrapping element.

<div id="comment-wrap"  class="slider">
    <label for="comment">Comment</label>
    <textarea cols="53" rows="10" id="comment"></textarea>
</div><!--/#comment-wrap-->

There are no major changes to the plugin, just a few tweaks. If you find anymore bug, please let me know.

View the Demo

Tags: , , ,
Posted in Web Design | 27 Comments »

Form Design with Sliding Labels

Tuesday, January 19th, 2010

Sliding Label banner

Please use version 1.1 of sliding labels with updated options and bug fixes at: http://www.csskarma.com/blog/sliding-labels-v2/

A few weeks ago I was reading an article on form UI by Luke Wroblewski of Yahoo!. For those who aren’t familiar with Luke, he (quite literally) wrote the book on good form design.

In the article, one certain section about placing labels inside of form fields stood out to me:

Because labels within fields need to go away when people are entering their answer into an input field, the context for the answer is gone. So if you suddenly forget what question you’re answering, tough luck—the label is nowhere to be found. As such, labels within inputs aren’t a good solution for long or even medium-length forms. When you’re done filling in the form, all the labels are gone! That makes it a bit hard to go back and check your answers. Luke Wroblewski

He brings up a good point. Generally speaking, you can look at a field that says “Tim Wright” and know that it was a field for your (my) name. But for long forms, yea, I do agree that you can forget some of the questions you answered.

For best practice, Luke talks about leaving your labels outside the form field so it’s always available to the user. I do think it’s a pretty good solution, but I think we can get a little more creative than that.

Enter: Sliding Labels

After reading that article it occurred to me that there’s no reason we can’t have the best of both worlds. I like how inline labels look, and I see Luke’s point about them disappearing as you fill out the form. But, we have jQuery, we know about progressive enhancement, and we have creative minds, so let’s build something that allows us to keep the label inline, but slide it off to the left (or up, whichever you prefer) rather than going away on click.

View demo (version 1.1)

The HTML

<form action="" method="post" id="info">
   <h2>Contact Information</h2>
   <div id="name-wrap" class="slider">
      <label for="name">Name</label>
      <input type="text" id="name" name="name">
   </div><!--/#name-wrap-->

   <div id="email-wrap"  class="slider">
      <label for="email">E&ndash;mail</label>
      <input type="text" id="email" name="email">
   </div><!--/#email-wrap-->

   <div id="street-wrap"  class="slider">
      <label for="st">Street</label>
      <input type="text" id="st" name="st">
   </div><!--/#street-wrap-->

   <div id="city-wrap"  class="slider">
      <label for="city">City &amp; State</label>
      <input type="text" id="city" name="city">
   </div><!--/#city-wrap-->

   <div id="zip-wrap"  class="slider">
      <label for="zip">Zip code</label>
      <input type="text" id="zip" name="zip">
   </div><!--/#zip-wrap-->

   <input type="submit" id="btn" name="btn" value="submit">
</form>

The only necessary items to make sliding labels (as I built it) work are the wrapper element (DIV in my case) and applying a class of “slider” to it (you can change this easily in the JavaScript).

At this point we have a pretty basic, and ugly form

slidinglabels no css

The CSS

body                       { font:12px/1.3 Arial, Sans-serif; }
form                       { width:380px;padding:0 90px 20px;margin:auto;background:#f7f7f7;border:1px solid #ddd; }
div                        { clear:both;position:relative;margin:0 0 10px; }
label                      { cursor:pointer;display:block; }
input[type="text"]         { width:300px;border:1px solid #999;padding:5px;-moz-border-radius:4px; }
input[type="text"]:focus   { border-color:#777; }
input[name="zip"]          { width:150px; }

/* submit button */
input[type="submit"]       { cursor:pointer;border:1px solid #999;padding:5px;-moz-border-radius:4px;background:#eee; }
input[type="submit"]:hover,
input[type="submit"]:focus { border-color:#333;background:#ddd; }
input[type="submit"]:active{ margin-top:1px; }

The only 100% necessary CSS in there is the position:relative on the wrapper element (DIV). The rest is basically cosmetic and you can mess with it as you see fit.

At this point you should have a pretty normal looking form with labels on top of their respective inputs.

labelslider no js

The jQuery

Now for the section everyone skipped to, provided you didn’t go straight to the demo (which I usually do).

$(function(){
$('form#info .slider label').each(function(){
	var labelColor = '#999';
	var restingPosition = '5px';

	// style the label with JS for progressive enhancement
	$(this).css({
		'color' : labelColor,
		 	'position' : 'absolute',
	 		'top' : '6px',
			'left' : restingPosition,
			'display' : 'inline',
    	               'z-index' : '99'
	});

	// grab the input value
	var inputval = $(this).next('input').val();

	// grab the label width, then add 5 pixels to it
	var labelwidth = $(this).width();
	var labelmove = labelwidth + 5;

	//onload, check if a field is filled out, if so, move the label out of the way
	if(inputval !== ''){
		$(this).stop().animate({ 'left':'-'+labelmove }, 1);
	}    	

	// if the input is empty on focus move the label to the left
	// if it's empty on blur, move it back
	$('input').focus(function(){
		var label = $(this).prev('label');
		var width = $(label).width();
		var adjust = width + 5;
		var value = $(this).val();

		if(value == ''){
			label.stop().animate({ 'left':'-'+adjust }, 'fast');
		} else {
			label.css({ 'left':'-'+adjust });
		}
	}).blur(function(){
		var label = $(this).prev('label');
		var value = $(this).val();
		if(value == ''){
			label.stop().animate({ 'left':restingPosition }, 'fast');
		}
	});
})
});

At this point, you should have a fully working sliding label form!

labelslider final

View demo (version 1.1)

Making sure everything is still usable without JavaScript is important (no matter what people say), it’s just a basic principle of progressive enhancement. Believe it or not, there are still people browsing without JavaScript (blackberry users – turned off by default). So creating the interaction in layers, as we did, will help it be past-proof.

Try it out and let me know what you think. So far I’ve used it on a password change form, so definitely let me know if you find a place to use it!

Tags: , , ,
Posted in Web Design | 130 Comments »

Conditional Animation Speed in jQuery

Friday, January 8th, 2010

Turtle

For years (and by “years”, I most likely mean “the years since I started using jQuery… maybe 2″), there’s been one aspect of jQuery that’s bugged the crap out of me, the animation speed.

View demo

We’ve all probably seen the problem that happens in many drop down menus of varying height. We set slideDown(300) (or whatever you set it to) on all the submenus and leave like that. Inevitably, menus grow and shrink based on the content and we get this weird and mildly annoying behavior of really fast moving tall menus vs. shorter menus that move painfully slow just because there’s not much content in there.

This problem stems from where we set the speed of the animation; the value isn’t actually a speed, it’s how long it takes (in milliseconds, I think) for the animation to finish. So you can see why you get varying behaviors based on the element height.

It’s true, that you can use the built-in speed values like “fast” and “slow”, but if you want more fine-grained control over your animation, you’ll have to use a value.

Problem Child

This is what our problem menu looks like all collapsed, just 2 clickable headings (h2) that will slide open to expose content (p)

animation collapsed

Normally our jQuery would look something like this:

$(function(){

$('h2').toggle(function(){
    /* get the next element */
    var next_element = $(this).next();

    /* open it  if it's closed */
    next_element.slideDown(500);
},function(){
    /* get the next element again */
    var next_element = $(this).next();

    /* close it if it's open */
    next_element.slideUp(500);
});

});

Note: just example code, I didn’t check to see if it actually works

This is our menu fully expanded. As you can see, the first item has a lot more content then the second. Using the code above will make menu #1 move noticeably faster than menu #2; which, to me, creates an odd user experience. Because you’re like “Why’s is moving so slow?”

animation expanded

So let’s see if we can’t fix that.

Ben Healy (Solution)

What we’re looking to do here is get the height of each collapsed item, do some JS math, and set a speed (animation time) value based on the height.

jQuery functions we’ll need

  • next()
  • height()
  • slideDown() / slideUp()
  • The Code

    $(function(){
    
    	/* Variables to set */
    	var id = '#heightCheck';
    	var click_element = 'h2';
    	var height_value = '100';
    	var tall_menu_speed = 400;
    	var short_menu_speed = 250;
    
    	/* System variables, probably don't change */
    	var target = id +' '+ click_element;
    	var menu_content = $(target).next();
    
    	/* Hide the element after the click_element, whether it's a
    	div, p, ul, whatever you choose to wrap the items in */
    	menu_content.hide();
    
    	$(target).toggle(function(){
    		/* save the menu items in a variable */
    		var this_menu = $(this).next();
    
    		/* get the menu height and save it */
    		var menu_height = this_menu.height();
    
    		/* Calculate the animation speed based on the element height */
    		/* if the height is greater than the height set above use the
    		tall menu height */
    		if(menu_height > height_value){
    			var speed = tall_menu_speed;
    
    		/* If it's smaller, use the short menu height */
    		} else if(menu_height < height_value) {
    			var speed = short_menu_speed;
    		}
    
    		/* slide the menu down */
    		this_menu.slideDown(speed);
    
    	},function(){
    		/* this is the same but reversed to close the menu */
    		var this_menu = $(this).next();
    		var menu_height = $(this).next().height();
    
    		/* Calculate the animation speed based on the element height */
    		if(menu_height > height_value){
    			var speed = tall_menu_speed;
    		} else if(menu_height < height_value) {
    			var speed = short_menu_speed;
    		}
    		this_menu.slideUp(speed);
    
    	});
    
    });

    That should give you a little more control over the menu speed. I'm sure it needs to be tweaked based on the menu you're using, but the general concept is there, and it should work pretty well. I hope it was helpful. Let me know if you have any additions to the code or suggestions to improve it.

    View demo

    Tags: , , ,
    Posted in Web Design | 2 Comments »

Quick Tip #2 – Bringing Back Search with jQuery

Monday, June 29th, 2009

article banner

This is something I use on all my projects now. It’s designed for a search box, but can be used with any sort of input field.

The great thing about this is that the field value “Search” will only come back onBlur if the field is empty (or doesn’t say “Search”). So if you started typing something it won’t erase your text, which is something that has always irritated me about search boxes.

Anyway, I’ve been sitting on this post for a while, but I really wanted to get it out. So here it is:

XHTML
<div id="search">
<form method="post" action="">
   <label for="field">search</label>
   <input type="text" id="field"/>
   <button type="submit">go</button>
</form>
</div><!--/search-->
jQuery
$("#search input").focus( function() {
if ($(this).val()=="Search") {$(this).val("");}
});

$("#search input").blur( function() {
if ($(this).val()=="") {$(this).val("Search");}
});

The word “Search” in the jQuery is case sensitive, so watch out for that.

Tags: ,
Posted in Web Development | 6 Comments »

This Week in Links 12/2

Monday, December 8th, 2008

article image

CSS Deployment 101

Reinhold Weber talks about how to compress a CSS file before you push it to the server. this will shave off some load time by reducing everything to one line and removing much of the white space. It also allows you to modularize your CSS without it effecting HTTP requests, because this script will also combine all files into one once it’s on the server.

Equal Height Columns with jQuery

A very useful bit of jQuery creating equal height columns. Pretty slick integration, I’ll be using this.

Web Directions North

Web Directions is a conference I went to last January, it was very cool. Possibly the best conference I’ve been to so far. It’s coming back this February in Denver; if you have the means, I highly recommend it.

Tags: , ,
Posted in News, Web Development | No Comments »

This Week in Links 11/11

Tuesday, November 11th, 2008

article image

Krop.com

I figured with the economy what it is and a lot of web folks looking for work I’d help out and post my favorite job site, Krop.com. I like this site for a few different reasons:

  • I found my current job there
  • They have a very simple interface
  • You can sign up for e–mail alerts based on a search term. When I was looking for a job in California I signed up to get e–mailed whenever a job came up in the search that had ", CA" in it. So I got all the California web jobs sent to me (and a few Canadian ones). It’s very nice.
13 Vital Skills for Every PHP Developer

There’s a lot about PHP that I just don’t remember off the top of my head and I need to look up. Luckily most of that is listed right here. This article contains things like Smarty, PayPal Integration, access control and caching with PHP.

jQuery Twitter Display

I’ll say it. I think jQuery is massively overused. But since you’re using it anyway and you want to display your Tweets, this is a plugin to do just that.

DocStoc

DocStoc is a repository for all kinds of documents. You can get everything from an example of a contract (hint hint to you freelancers) to the guitar tabs for "Smell Like Teen Spirit"

I’m not sponsored by any of these sites or services.

Tags: , , ,
Posted in Uncategorized | 1 Comment »

This Week in Links 10/27

Monday, October 27th, 2008

article banner

Better CSS Font Stacks

A good article on how to jazz up your stacks to try and take advantage of users who have more fonts installed. I’m all for this, and as long as it’s done carefully, can get a nice version of progressive enhancement.

5 Terrible SEO Ideas

Richard Bradshaw goes over some trendy (and terrible) things that are common in SEO such as: keyword stuffing, dupe content, link farms, splash pages, and cloaking.

Fun with Overflows

I think this is a great idea (check out the demo). It creates a very similar interface to that of Plurk, the twitter competitor.

Tweet What you Spend

This is a pretty cool service that uses the Twitter API to track spending. I know it can seem kind of geeky (as is reading articles about CSS…), but tracking your spending is a great way to save money, it gives you a lot of power when you know exactly how your paycheck disappears every month. Provided you don’t mind sharing your expenses with the Twitterverse, this is a good service and very easy to use.

Tags: , , , , , ,
Posted in News, Web Development | 1 Comment »

This Week in Links 10/15

Wednesday, October 15th, 2008

article banner

One Click, The Importance of UI

Many times my link lists back up a few weeks and I have to revisit an article to really remember what it was about. When I did that to this one, I moved it up to the top of the list. It’s a very interesting article on user interface and the importance of the click. A must-read in my opinion.

Pixel Precision with Diagnostic CSS

A technique for mocking up a design.

Mint Analytics

Analytics software I found while muddling through the An Event Apart web site.

Tags: , , ,
Posted in News, Web Development | No Comments »

Active navigation with jQuery

Wednesday, October 8th, 2008

banner image

I was building a site last week and came across some jQuery code for active navigation. It’s very simple and works real well. I’m using it on some secondary navigation and still using my body class for the main nav.

Active navigation with a body class
body.home #nav ul li.navhome{font-weight:700;}

So I’m still doing that, but then for the internal page navigation, rather than loading the CSS up with long declarations for the numerous sub nav links, I used this jQuery:

Active vavigation with jQuery
$("#nav a").each(function() {
var hreflink = $(this).attr("href");
if (hreflink.toLowerCase()==location.href.toLowerCase()) {
	$(this).parent("li").addClass("selected");
}

Breaking it down

Let’s try this line by line for those who want to know what’s happening here.

This targets each link in contained in #nav.

$("#nav a").each(function() {

This line just saves the href attribute of each #nav a to a variable. It makes the code a little cleaner and easier to work with.

var hreflink = $(this).attr("href");

This converts the href of each link in #nav, makes it lowercase (it should be already, but just in case) and checks the current URL of the page and sees if they match. Also making the current page URL lowercase.

if (hreflink.toLowerCase()==location.href.toLowerCase()) {

If the current URL matches the href for one of the links it looks to the parent element (in this case it’s a list item) and adds a class of “selected” to it.

$(this).parent("li").addClass("selected");

This is just closing the function, I really don’t know why I didn’t include it in the above code for the purpose of this post. But no matter.

}

Issues

The only problem I ran into with this was that you have to make sure the you use a consistent href for pages.

For example

If you’re sub nav contains a link to http://www.csskarma.com/contact/, you have to make sure that you don’t link to http://www.csskarma.com/index.php; or the active navigation won’t work.

It’s not a huge deal, but definitely something to be aware of, I just had to go through a site and clean up a bunch of links up because I applied this jQuery pretty late in development. You can probably rework the code to strip out the file name and extension or do it with some PHP, if you’d like.

Actually, if anyone does that, let me know and I’ll update this post with the code.

Tags: , , ,
Posted in Web Development | No Comments »

This Week in Links 10/6

Monday, October 6th, 2008

article banner

Successfully Present Your Web Designs to Clients

Dave Woods put together a nice article in response to Andy Clarke’s article on static visuals. I’m linking this one up because I think a lot have already read Andy’s and I think Dave did a nice job on this one.

Feature your Products with jQuery

This is a cool jQuery trick from a blog I just started reading a couple weeks ago.

Writing Maintainable CSS

Unfortunately, my link posts are a little backed up right now, so this is probably a week old at this point. But it’s a direct link to the slide show on writing maintainable CSS. I disagree with some of it, but overall, a good presentation.

Space Madness

Ariel is, from what I can gather, awesome, and a consultant for NASA. In this post she described how Twitter is being used on Neptune!

Tags: , , , ,
Posted in News, Web Development | 1 Comment »

« Older Entries |

New from the blog

Are My Sites Up? authenticjobs.com