My jQuery Snippets
The following is a collection of my jQuery snippets. These snippets are little things I don't want to forget or helpful scripts I've come across during work. This article isn't meant to be a tutorial, but I placed helpful links and JSFiddle's for further assistance.
Contents
- Widget Related
- Unclickable Children
- Hide Element If User Clicks Outside
- Stop Link from Being a Link
- Click Events for DOM Added after Page Load
- Math/Tables
- Rounding Numbers
- Conditional Formatting in Tables
- Removing/Adding Currency Formatting
- Collect Row as Array
- Sum of Every Table Row
- Forms
- Reveal Content Based on Radio Selection
- Checkbox Manipulation
- Expanding Textarea to Fit Text
- Simple Spinner
- Reponsive
- Dynamically Sized Columns
Basics
jQuery starting template
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
$('document').ready(function() {
// insert code here
});
</script>
Creating a function
function sample(x, y) {
$('<p>This is a ' + x + ' test. ' + y + '</p>').prependTo('p');
}
sample('simple', 'It\'s easy.');
If statement
if (divWidth == '1') {
// do something
} else {
// do something else
}
If element contains something
if ($(this).find('ul').length > 0) {
// do something
}
CSS
Single CSS style
$('.demo td:nth-child(3)').css('width','80px');
Multiple styles
$('.demo tr td:nth-child(2)').css({'width':'580px','padding-top':'15px'});
Multiple styles packaged into a variable
var styles = {'margin-top':'100px', 'font-weight':'bold', 'font-size':'30px'};
$('.demo').css(styles);
Loop
The following is the loop script. In the sample, “10” would be the amount of times the loop repeats. Keep in mind, though, that if you just want to run jQuery through a series of like elements then it's better to use the Each function.
for(var i = 0; i < 10; i++) {
// do something
}
The loop amount could be set as a variable as well.
var loopamount = 10;
for(var i = 0; i < loopamount; i++) {
// do something
}
Data Attributes
Usage in HTML
<a href="demo.html" data-country="united states" data-state="florida">Sample</a>
Setting it to a variable
var sample = $('#dropdown').data('country')
Changing it
$('a').attr('data-country', 'mexico');
In an If statement, if data equals x
if ($(this).data('door') == 'open') {
// do something
}
In an If statement, if data is not equal to x
if ($(this).data('door') != 'open') {
// do something
}
Target all elements with specific data attribute
$('[data-demo]').on('click', function() {
// do something
});
Target all elements with specific data attribute & its text
$('[data-demo="some-text"]').on('click', function() {
// do something
});
Confused? Learn more about data attributes with jQuery
Avoiding parent().parent().parent()...
Avoid typing parent() over and over with “parents()” and “eq()”. Type parents() then put eq() with the number of parent()'s -1. For example, if you're using 3 parent()'s do the following.
$(this).parents().eq(2).find('p');
Using Index and Eq
This is important to know for targeting elements. To pass around and use an element's index, you need to use CSS's eq.
var demo = $(this).index();
$('li:eq(' + demo + ')').toggleClass('red');
Sticky Navigation
This is actually pure JavaScript, not jQuery. This script makes a side navigation stick to the top of the page upon scroll. This is appropriate for when you have a column reserved entirely for the navigation to pass through. Sticky navigations are a popular effect - there are many sticky plugins available if this script doesn't work out for you.
var menu = document.querySelector('.menu')
var menuPosition = menu.getBoundingClientRect().top;
window.addEventListener('scroll', function() {
if (window.pageYOffset >= menuPosition) {
menu.style.position = 'fixed';
menu.style.top = '0px';
} else {
menu.style.position = 'absolute';
menu.style.top = '';
}
});
Forking from above, if the navigation that you need to sticky is between the header and content then that requires a few extra steps. The following script creates an empty DIV to correct an awkward jump that occurs when the navigation switches to its sticky state.
var menu = document.querySelector('.menu');
var menuPosition = menu.getBoundingClientRect();
var placeholder = document.createElement('div');
placeholder.style.width = menuPosition.width + 'px';
placeholder.style.height = menuPosition.height + 'px';
var isAdded = false;
window.addEventListener('scroll', function() {
if (window.pageYOffset >= menuPosition.top && !isAdded) {
menu.classList.add('sticky');
menu.parentNode.insertBefore(placeholder, menu);
isAdded = true;
} else if (window.pageYOffset < menuPosition.top && isAdded) {
menu.classList.remove('sticky');
menu.parentNode.removeChild(placeholder);
isAdded = false;
}
});
Fade+Expand Animation
This script toggles an animation that fades and expands/collapses at the same time.
$.fn.slideFadeToggle = function(speed, easing, callback) {
return this.animate({opacity: 'toggle', height: 'toggle'}, speed, easing, callback);
};
$("#something").click(function() {
$(this).slideFadeToggle();
});
However, you can't use the above script when you're using a hover because you'll run into cue problems. In that case, use HoverFlow and the following script.
$('.button').hover(function(e) {
$(this).next().hoverFlow(e.type, { opacity: 'toggle', height: 'toggle' }, 'fast');
}, function(e) {
$(this).next().hoverFlow(e.type, { opacity: 'toggle', height: 'toggle' }, 'fast');
});
Hover or Click Button
This is useful for responsive sites.
var hoverOrClick = function () {
// reveal something
}
$('.options').click(hoverOrClick).hover(hoverOrClick);
However, the above code doesn't play nice with multiple animations such as with my Fade+Expand Animation. Using HoverFlow, the following script would make a hover/click button work with multiple animations.
// Hover
$.fn.slideFadeToggle = function(e) {
return this.hoverFlow(e.type, {opacity: 'toggle', height: 'toggle'}, 'fast', 'linear', function() {});
};
var hoverExpand = function (e) {
$(this).find('ul').slideFadeToggle(e);
}
$('.dropdown').hover(hoverExpand);
// Click
$('div').click(function() {
if ($(this).find('ul').is(':visible')) {
$(this).find('ul').hide();
} else {
$(this).find('ul').show();
}
});
Current Page Style & :not
Using :not can be very useful with jQuery. One such use is when you're using a current-page style in a jQuery animated navigation. You can apply the jQuery animation on every navigation link except the one you set as the current page. Also, in this sample I'm using the Color animation jQuery-plugin for an elegant background color transition.
$('#navigation li:not(#current) a').hover(
function () {
$(this).animate({
'background-color': '#00bff3',
'padding-left': '20px'
}, 'fast', 'linear', function () {});
},
function () {
$(this).animate({
'background-color': '#0072bc',
'padding-left': '10px'
}, 'fast', 'linear', function () {});
});
Scroll Page
Scroll to bottom of page
$('html, body').animate({scrollTop:$(document).height()});
return false;
Scroll to top of page
$('html, body').animate({scrollTop:0});
return false;
Scroll a little bit
$('html, body').animate({scrollTop:'-20px'}, 'slow');
return false;
Scroll to an element
$('html,body').animate({ scrollTop: $('#target').offset().top}, 'medium');
return false;
In addition to above, in some cases you may need to scroll higher to the parent element.
$('html,body').animate({ scrollTop: $(this).parent().parent().offset().top}, 'medium');
return false;
Appear in Domino Effect
A quick script to make a group of elements fade in one by one with a domino effect animation.
$('div').hide();
$('div').each(function(i) {
$(this).delay(100*i).fadeIn('slow');
});
Basic Timeline Animation
This is the most basic method of timeline based animation. The number you enter for the delay would be the element's position in the timeline. However I don't recommend this script for complex animations. There are several great jQuery animation plugins out there such as Spritely and Collie.
block1 = $('#block1');
block2 = $('#block2');
block1.delay(400).animate({'left':300}, 'slow');
block2.delay(400).animate({'top':200}, 'slow');
block2.delay(700).animate({'width':200,'height':200}, 'slow');
block1.delay(900).animate({'left':-200,'opacity':0}, 'slow');
block2.delay(1000).animate({'top':-200,'height':-200,'opacity':0}, 'slow');
Random Element
Grab a random element from a group.
var count = $('.blocks div').length;
var randomer = Math.ceil(Math.random() * count)
$('.blocks div').each(function () {
var pos = $(this).index() + 1;
$(this).hide();
if (pos == randomer) {
$(this).show();
}
});
Unclickable Children
When you've applied a click event to an element, this script disables the click event for child elements. For example, this is useful when you have an accordion with buttons inside the click area.
$('h2').click(function () {
$(this).toggleClass('demo');
});
$('h2 span').click(function (e) {
e.stopPropagation();
});
Hide Element If User Clicks Outside
Hide an element if the user clicks anywhere on the page outside of it. This script is useful if you're creating a DIV driven form.
$(document).mouseup(function (e) {
var container = $("div");
if (!container.is(e.target) && container.has(e.target).length === 0) {
container.hide();
}
});
Stop Link from Being a Link
I usually prefer making a DIV or other element a button for jQuery events, but sometimes I use an anchor. In the JSFiddle I have you scroll down to the bottom on the page to show you that the page doesn't refresh when you click the anchor.
$('a').on('click', function(e) {
e.preventDefault();
})
Click Events for DOM Added after Page Load
When working with jQuery UI, jQuery Mobile, AJAX, or other content dynamically slapped onto the page after it has loaded, a common problem is being unable to add click events to such content. This is resolved with the following; it's called binding.
$(document).on("click", ".sample-div", function(e) {
// enter action here
});
Rounding Numbers
Rounding up, rounding down, and rounding to the nearest 10.
$("#roundDown").text('Rounded down: ' + Math.floor(number / 10) * 10);
$("#roundUp").text('Rounded up: ' + Math.ceil(number / 10) * 10);
$("#roundNearest").text('Rounded to nearest: ' + Math.round(number / 10) * 10);
Conditional Formatting in Tables
Color a table cell if a number is greater than or less than the number you set.
$('td').each(function () {
if($(this).text() >= 200) {
$(this).css({'color':'red','font-weight':'bold'});
}
if($(this).text() <= 100) {
$(this).css({'color':'blue','font-weight':'bold'});
}
});
Color a table cell based on the result of comparing two cells.
$(".total").each(function() {
var year1 = parseInt($(this).prev().prev().text().replace(/[^0-9\.]+/g,""), 10);
var year2 = parseInt($(this).prev().text().replace(/[^0-9\.]+/g,""), 10);
if (year1 > year2) {
$(this).css({'color': 'red'});
} else {
$(this).css({'color': 'green'});
}
});
Removing/Adding Currency Formatting
Removing currency formatting and then adding it back. To add the currency formatting I'm using the Format Currency Plugin.
var source = $('#source').text();
var removeCurrency = source.replace(/[^0-9\.]+/g,""); // Removes currency
$('#removed').text(removeCurrency);
$('#removed').formatCurrency('#return'); // Adds currency and sends back to DOM
Collect Row as Array
Grabs all the items in a table row and compiles it into an array.
var pets = [];
$('#secondRow td').each(function(i, elem) {
pets.push($(elem).text());
});
$('p').html('Your array contains: ' + pets);
Sum of Every Table Row
Runs through every table row and adds up the total.
$('tbody tr').each(function() {
row_total = 0;
$(this).find('td:not(.total)').each(function() {
row_total += parseInt($(this).text(), 10);
});
$('.total',this).text(row_total);
});
Reveal Content Based on Radio Selection
The basis of making a form conditional.
$("input[name$='search']").click(function(){
var radio_value = $(this).val();
if(radio_value=='Hotel and flight') {
$(".location").slideDown("medium");
}
else if(radio_value=='Hotel only') {
$(".location").slideUp("medium");
}
});
$(".location").hide();
Checkbox Manipulation
Do something if a checkbox is checked.
$('input[type="checkbox"]').click(function() {
if ($(this).is(':checked')) {
// do something
}
});
Check or uncheck a checkbox.
$('.myCheckbox').prop('checked', true); // Check it
$('.myCheckbox').prop('checked', false); // Uncheck it
Expanding Textarea to Fit Text
Expands the height of the textarea to fit the text as the user is typing.
$("#demo").mousemove(function (e) {
var myPos = $(this).offset();
myPos.bottom = $(this).offset().top + $(this).outerHeight();
myPos.right = $(this).offset().left + $(this).outerWidth();
if (myPos.bottom > e.pageY && e.pageY > myPos.bottom - 16 && myPos.right > e.pageX && e.pageX > myPos.right - 16) {
$(this).css({ cursor: "nw-resize" });
} else {
$(this).css({ cursor: "" });
}
})
.keyup(function (e) {
while ($(this).outerHeight() < this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth"))) {
$(this).height($(this).height() + 1);
};
});
Simple Spinner
A spinner uses arrow buttons to increment a number. In this spinner, the left or right arrow disables if the minimum or maximum number is the current number. Spinners are good for mobile sites.
// Set variables
var currentValue = parseInt($('input').val(), 10);
var minNum = 1;
var maxNum = 4;
// On page load, disable arrow if min or max is default value
if (currentValue == minNum) {
$('.leftArrow').addClass('dim');
}
if (currentValue == maxNum) {
$('.rightArrow').addClass('dim');
}
// Click events
$('.leftArrow').click(function() {
if (currentValue != minNum) {
currentValue--;
$('input').val(currentValue);
$('.rightArrow').removeClass('dim');
}
if (currentValue == minNum) {
$('.leftArrow').addClass('dim');
}
});
$('.rightArrow').click(function() {
if (currentValue != maxNum) {
currentValue++;
$('input').val(currentValue);
$('.leftArrow').removeClass('dim');
}
if (currentValue == maxNum) {
$('.rightArrow').addClass('dim');
}
});
Dynamically Sized Columns
This script resolves the need to have 100% height on an element (or row of elements), but the height takes into account elements above and/or below that have a fixed height. This is responsive because the faux 100% height is recalculated every time the user adjusts the browser window. In the JSFiddle resize the browser to see it in action.
var callback = function () {
var windowSize = $(window).height();
var headingHeight = $('.header').height();
var wrapperHeight = windowSize - headingHeight;
$('.wrapper div').height(wrapperHeight);
};
$(document).ready(callback);
$(window).resize(callback);
Further Reading
Here are some good links for learning jQuery:
- Try jQuery - Really cool interactive tutorials.
- Code Academy - Another place for nifty interactive tutorials.
And here are some recommended books:
- jQuery: Novice to Ninja. It's an excellent book. Sitepoint is my favorite publisher. Everything is presented with realworld examples.
- JavaScript and JQuery: Interactive Front-End Web Development - A beautiful full color book that teaches code in a visual, fun way.