For the last few weeks I’ve been collecting tiny morsels of jQuery and straight JavaScript that I’ve needed for building sites. I had found myself needing the same small scripts over and over. Rather than rewriting and checking an API/plugin reference, now I can just copy from this list.

jQuery One-Liners (Sort of)

Most of what I’ve collected here are only a few lines each, and some are very simple. It originally was going to be a collection of one-liners. For readability’s sake, I’m not sticking to that rule.

If you’re not a programmer at heart, or a jQuery master, perhaps some of this will help you accomplish some simple scripting tasks. If you are, you’ve probably skipped this already, copied the code you needed, and hightailed it out of here. Note that the selectors are all set to names that I’ve used, or placeholders designated by capital letters.

I’ve kept it all in one block of commented JavaScript, for easy copy-pasting [edit: Now under nice H2s with better descriptions]. I’m using this too, and I will likely add more in the future. If you have an addition, leave it in the comments.

Did you Know?: You can use the :input selector to target all input, textarea, select and button elements.

DOM Ready

Waits until the DOM is ready, so scripts that manipulate it can be executed. It’s likely that most of your jQuery initialization will be contained in this.

// Standard Usage
$(document).ready(function() {
  // Your code goes here
});

// When in NoConflict Mode: You can still remap the dollar sign alias, 
// so you can use it within this code block.
jQuery.noConflict();
jQuery(document).ready(function($){
  // Your code goes here
});

Open Google Map in Colorbox

Colorbox is my lightbox of choice lately. Add &output=embed to the end of your google map link that has this class:

$("a.view-map").colorbox({ iframe:true, width:"80%", height:"80%" });

Checkbox Must be Checked to Submit Contact Form

This gives a JavaScript alert and does not submit the form when a required checkbox is not checked. Used for disclaimers and such. Change #contact-submit and #contact-side to your checkbox and specific form container.

$(function() {
	$('#contact-submit').click(function(e) {
		var checked = $('#contact-side :checkbox:checked').length;
		if (checked == 0) {
			alert('Before this form is sent, you must agree to the disclaimer.');
			e.preventDefault();
		} else {
			$('#contact-side form').submit();	
		}
	});
});

Form Inputs Placeholders that Clear and Restore on Click (Watermarks)

I use this one a lot. While HTML5 gives us the placeholder attribute, older browsers need a JavaScript solution. This one is real quick and works. Set the input’s title attribute to the value you want displayed, and give it a class of txt.

// CLEAR ON FOCUS
// This is an older method. I would now use modernizr with a placeholder polyfill.
// set all default value according to title attribute. 
$(".txt").each(function(){
  $(this).val($(this).attr("title"));
});
// clear input.text on focus, if still in default
$(".txt").focus(function() {
  if($(this).val()==$(this).attr("title")) {
	$(this).val("");
  }
});
// if field is empty afterward, add text again
$(".txt").blur(function() {
  if($(this).val()=="") {
	$(this).val($(this).attr("title"));
  }
});

Add a Class to All Mailto Links

$("a[href^='mailto:']").addClass("email");

Add “Scroll to Top” Link for Tall Pages

Why have scroll to top on really short pages? Change the number 800 to whatever minimum height you want.

if ( $("#content").height() > 800 ) {
     $("#content").append(' ');
}
$('.scrolltop').click(function(event) {
     $('html, body').animate({scrollTop: '0px'}, 0);
    event.preventDefault();
});

Get the Currently Selected Option Value of a Select List

$("#SELECTIDHERE option:selected").val();

Dynamically Add ‘last’ Class to last LI in each child UL.

$("#aside ul").each(function(){ $(this).find("li:last").addClass('last'); });

Add First and Last Classes

For ye old browsers that do not support the CSS pseudo-elements first-child and last-child

$("#NAV ul li:last").addClass('last');
$("#NAV ul li:first").addClass('first');

Dynamically Add “Print Page” Link

Adds Printable Icon/Link to H1, and bring up print dialog when clicked.

$("#CONTENT h1:first").append('Print');
$("#CONTENT h1 a.print").click(function(event){
    event.preventDefault();
    window.print();
});

Add External Class to All External Links

Creates an “:external” selector and applys a class to all links with different hostnames. Note that you may have to change this to exclude your subdomains.

// Put this outside your $(document).ready()
$.expr[':'].external = function(obj){
    return !obj.href.match(/^mailto:/)
            && (obj.hostname != location.hostname);
};
// Add 'external' CSS class to all external links. "not()" is optional.
$('a:external').not('.EXCLUDEDCLASSHERE').addClass('external');

Remove all disabled form fields

$("#MYFORM").find(":input").removeAttr("disabled");

Get Filename from URL/Path

Reads the source attribute of an image, and finds the filename.

var imageName = $("#YOURSELECTOR").attr('src');
imageName = imageName.substr(imageName.lastIndexOf("/") + 1);

Nice Vertically Expanding Element on Hover, with Easing

Requires the jQuery easing plugin to use “easeOutQuad”. The element would start out with a height of 205px in this example.

$("ul.areas li div").mouseover(function(){
$(this).stop().animate(
	{height:'227px'},
	{queue:false,duration:200,easing:'easeOutQuad'}
)});
$("ul.areas li div").mouseout(function(){
$(this).stop().animate(
	{height:'205px'},
	{queue:false,duration:350,easing:'easeOutQuad'}
)});

Updated on March 14th, 2012

Comments on this Article

  1. Kaizoku says:

    Thanks, but seems like the ampersand has been replaced with entities in the code.

    • Josh says:

      Thanks, this was fixed.

Leave a Reply

You can use the <pre> tag to post a block of code, or <code> to highlight code within text.