Stupid jQuery Tricks

Dec14
Stupid jQuery Tricks

If you are like I am and use jQuery to add functionality or enhance your site, you're almost always looking to learn something new or different ways to add a cool new function using the most popular JavaScript library out there. While none of these functions are actually stupid, they will show you some popular tricks to add effects and features to your site.

Disappearing Search Box Text

Every site has one, a search box. Some do it right and others don't, nothing ruins usability more than clicking in a search box and having to press the delete key to remove the default search text then type before being sent on your way. Here is a simple function to gray out the text, remove it when the user clicks and then put it back when they are done.

Disappearing search text on Smashing Magazine

Disappearing search text on Smashing Magazine

The Code

$(document).ready(function() {
$("input.text1").val("Enter your search text here");
//attach function to input and make text grayed out on page load
textReplacement($('input.text1').css("color", "#999"));
});

// the function:
	function textReplacement(input){ //input focus text function
 	var originalvalue = input.val();
 	input.focus( function(){
  		if( $.trim(input.val()) == originalvalue ){ input.val('').css("color", "#000"); }
 	});
 	input.blur( function(){
  		if( $.trim(input.val()) == '' ){ input.val(originalvalue).css("color", "#999"); }
 	});
}

The Inputs

<input type="text" id="query" class="text1" value="" /><input type="submit" value="Search" />

Give It A Try

Disappearing Search Box Text on Multiple inputs

Reader Brain commented and wanted to know how to do this with multiple inputs. By adding the each() function you can cycle through each input individually.

The Code

$(document).ready(function() {
$("input.text").val("Enter your search text here");
	 $("input.text").each(function() {
		//attach function to input and make text grayed out on page load
		textReplacement($(this).css("color", "#999"));
		});
});

// the function:
	function textReplacement(input){ //input focus text function
 	var originalvalue = input.val();
 	input.focus( function(){
  		if( $.trim(input.val()) == originalvalue ){ input.val('').css("color", "#000"); }
 	});
 	input.blur( function(){
  		if( $.trim(input.val()) == '' ){ input.val(originalvalue).css("color", "#999"); }
 	});
}

The inputs

<input type="text" class="text" value="" /><input type="submit" value="Search" />
<input type="text" class="text" value="" /><input type="submit" value="Search" />

Give It A Try

Smooth Page Scroll

This next snippet will make any link with a hash (#) scroll to a specified id of that name with a smooth animation. I am using this code on the top and bottom of each post, click the comments bubble or the back to top link and watch the page magically scroll up and down. Credit for this goes to Karl Swedberg of Learning jQuery which is an awesome site by the way.

Smooth scrolling back to top link

Smooth scrolling back to top link

The Code

 $('a[href*=#]').click(function() {
 if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
 && location.hostname == this.hostname) {
   var $target = $(this.hash);
   $target = $target.length && $target
   || $('[name=' + this.hash.slice(1) +']');
   if ($target.length) {
  var targetOffset = $target.offset().top;
  $('html,body')
  .animate({scrollTop: targetOffset}, 900);
    return false;
   }
 }
  });

The Links

<a href="#left-container">top of post</a>

Give It A Try

top of post

Display Comment Author Url on Hover

If you've ever visited Web Designer Wall, in the comments section the authors url is displayed when hovering over their name with an arrow next to it. A simple jQuery solution would be to wrap your author url in a span, hide it with css and show it on hover with jQuery. I might add that this can be done with CSS also, but it doesn't work properly in older browsers.

Author url hover using jQuery on Web Designer Wall

Author url hover using jQuery on Web Designer Wall

The Code

$(document).ready(function() {
$(".author a").hover(function() {
		$(this).next("span").css({ display: "inline"});
	}, function() {
		$(this).next("span").css({ display: "none"});
	});
});

The Markup

<div class="author"><a class="url" rel="external nofollow" href="http://www.vagrantradio.com">Jason Pant</a> <span class="hidden">&#8594; http://www.vagrantradio.com</span></div>

The Css

.author span.hidden {
	display:none;
	font-size:small;
}

Try It Out

Jason Pant

Open External Links in a New Window/Tab

There have been many discussions on opening external links in a new window. Either bad or good, it can be done by appending the target blank or rel external attributes using jQuery.

This function simply finds each instance of http:// on the page and skips any instance of http:// with your domain name attached to it.

The Code

$("a[href^=http://]").not("a[href^=http://www.yourdomain]").attr("target", "blank");
$("a[href^=http://]").not("a[href^=http://www.yourdomain]").attr("rel", "external");

Try It Out

http://twitter.com/jquery

That's All Folks

And that about does it for this post. You should subscribe to my Rss feed to get more jQuery, Ajax and other tutorials coming in the future. Thanks for reading and feel free to share any cool tricks or links in the comments.

Author: Jason Pant

Hi, I'm Jason. A front end developer from Grand Rapids, Michigan, and founder of VagrantRadio. I enjoy working with Css, jQuery, Php, learning new techniques in Photoshop and you should follow me on Twitter or Google Buzz.

Enjoy this post?

If you enjoyed this post, please take a second to promote it via the various social bookmarking sites below. Don't forget to subscribe to the RSS Feed for more interesting articles. Thanks for visiting!

submit to delicioussubmit to diggsubmit to facebooksubmit to redditsubmit to stumbleuponsubmit to twittersubmit to mixxAdd to Google Buzzsubmit to Design Moosubmit to designfloatemail this someone

17 Comments

  1. James Padolsey

    What exactly is the point in a “captcha” that only works when JavaScript is enabled? Doesn’t that kinda miss the point?

  2. Zach Leatherman

    I don’t think your JavaScript based CAPTCHA is technically sound.

    1. I don’t believe spam-bots run JavaScript, so adding a check in JavaScript isn’t going to matter.
    2. I can’t imagine that spam-bots wouldn’t run headless (so putting the disabled attribute on a button isn’t going to matter).

  3. Mathias Bynens

    FYI: The “Display Comment Author Url on Hover” trick can be done through CSS as well, although it may not work in older browsers that way. Using JavaScript, it obviously won’t work for users who have JavaScript disabled.

  4. Jason Pant

    @James and Zach:

    Thank you for both of your points, is there something you would suggest doing differently to improve it?

    @Mathias: It can be done in CSS and I left that part out. It won’t work in older browsers, but then again, not a one of these will work with JavaScript disabled either. I can’t really think of a cross-browser, bullet-proof solution, can you?

  5. Steve Lacey

    I agree with the comments above, the jQuery captcha hurts my head; that’s pointless and certainly isn’t going to stop any spambots.

    Also regarding the ‘Display Comment Author Url on Hover’ trick; whilst it can be achieved with CSS; as stated it wouldn’t work easily in all browsers (without the span residing inside the anchor at least). A better jQuery solution would be:

    $(document).ready(function() {
    $(“.author a”).each(function() {
    $(this).next(“span”).hide();
    $(this).hover(function() {
    $(this).next(“span”).show();
    }, function() {
    $(this).next(“span”).hide();
    });
    });
    });

    And then to not hide the span in CSS, at least that way it would degrade gracefully so users without JavaScript don’t lose that information.

    • Jason Pant

      Steve,

      Thanks for the input on the capcha, I certainly don’t claim to know everything and you guys have definitely educated me. I will update the author hover with your suggestions.

      • Steve Lacey

        Your idea for captcha could be implemented successfully:

        An apt solution would be to render a question via the server-side language and have it store the answer in a session, then when a user enters an answer in the text box, use AJAX to check if they’re correct (enabling the submit button if so).

        Then on submit simply check again server-side that the value matches what is in the session, aiding spambot prevention as intended.

  6. Jaan

    nice post jason

  7. Design Informer

    This is great. You should do another post like this but with more tricks! :)

  8. Brain

    Hey,
    Nice tutorials, i liked the one with the dissapearing and reappearing text alot..
    how can you make it work for more then one inputbox?

    cheers

  9. HerVonTenia

    The smooth page scroll is awesome and very simple to integrate… I think I’ll use for all my websites. Thank you so much =)