10 Useful and Time Saving JavaScript Snippets

10 Useful JavaScript Snippets

JavaScript evolves at a really fast pace. With such a big wave of fresh JavaScript technology splashing the web everyday it’s a daunting task to keep up to date with all of it. jQuery is the preferred library due to its undeniable popularity, although some scripts are written in pure JavaScript.

10 Useful JavaScript Snippets

In this article we are going to cover 10 useful scripts that will save you some time when solving common problems. Most of these snippets are good to copy & paste but feel free to analyze, strip, mix, share, or adapt them to your own workflow.

10 Useful JavaScript Snippets

1. Maximum width or height in a set of elements

This script is very useful to make equal height columns or equal width rows easily:

var getMaxHeight = function ($elms) {
  var maxHeight = 0;
  $elms.each(function () {
    // In some cases you may want to use outerHeight() instead
    var height = $(this).height();
    if (height > maxHeight) {
      maxHeight = height;
  return maxHeight;


$(elements).height( getMaxHeight($(elements)) );

To get the maximum width, replace all occurrences of height and Height with width and Width respectively.

Demo: Equal height columns

2. Validating a date effectively

The date library in JavaScript is often too simple and usually not enough for advanced date formatting. Although there are many JS libraries that make working with dates much easier, sometimes you just want something simple that validates a date from a string. In that case you can use the following script. It lets you validate a date with any delimiter character and 4 digit year.

function isValidDate(value, userFormat) {

  // Set default format if format is not provided
  userFormat = userFormat || 'mm/dd/yyyy';

  // Find custom delimiter by excluding
  // month, day and year characters
  var delimiter = /[^mdy]/.exec(userFormat)[0];

  // Create an array with month, day and year
  // so we know the format order by index
  var theFormat = userFormat.split(delimiter);

  // Create array from user date
  var theDate = value.split(delimiter);

  function isDate(date, format) {
    var m, d, y, i = 0, len = format.length, f;
    for (i; i < len; i++) {
      f = format[i];
      if (/m/.test(f)) m = date[i];
      if (/d/.test(f)) d = date[i];
      if (/y/.test(f)) y = date[i];
    return (
      m > 0 && m < 13 &&
      y && y.length === 4 &&
      d > 0 &&
      // Check if it's a valid day of the month
      d <= (new Date(y, m, 0)).getDate()

  return isDate(theDate, theFormat);

The following will return false because November doesn’t have 31 days.

isValidDate('dd-mm-yyyy', '31/11/2012')

Demo: Validating a date input

3. Setting breakpoints for responsive design

This utility is a simple approach to set width breakpoints when working on responsive designs. It’s a quick way to relate CSS media queries in your JavaScript code as you go.

function isBreakPoint(bp) {
  // The breakpoints that you set in your css
  var bps = [320, 480, 768, 1024];
  var w = $(window).width();
  var min, max;
  for (var i = 0, l = bps.length; i < l; i++) {
    if (bps[i] === bp) {
      min = bps[i-1] || 0;
      max = bps[i];
  return w > min && w <= max;


if ( isBreakPoint(320) ) { 
  // breakpoint at 320 or less
if ( isBreakPoint(480) ) { 
  // breakpoint between 320 and 480

The following demo shows the script in action with some CSS media queries. When a box is clicked it will alert the device that matches the current window width. As the window is resized, the CSS media queries will change the color of the boxes and the JS breakpoints will make sure the correct device is alerted. It’s a very simple example but try to imagine the possibilities.

Demo: Responsive breakpoints with media queries

4. Highlighting text

There are many jQuery plugins to highlight text but I find this technique powerful, easy to implement and customize and it can work without any libraries, just plain JavaScript. The script returns the original text with the terms wrapped in a tag so they can be styled with CSS.

function highlight(text, words, tag) {

  // Default tag if no tag is provided
  tag = tag || 'span';

  var i, len = words.length, re;
  for (i = 0; i < len; i++) {
    // Global regex to highlight all matches
    re = new RegExp(words[i], 'g');
    if (re.test(text)) {
      text = text.replace(re, '<'+ tag +' class="highlight">$&</'+ tag +'>');

  return text;

You may also want to unhighlight text.

function unhighlight(text, tag) {
  // Default tag if no tag is provided
  tag = tag || 'span';
  var re = new RegExp('(<'+ tag +'.+?>|<\/'+ tag +'>)', 'g');
  return text.replace(re, '');

These two snippets would make a great start to build your own text highlighting plugin.


$('p').html( highlight(
    $('p').html(), // the text
    ['foo', 'bar', 'baz', 'hello world'], // list of words or phrases to highlight
    'strong' // custom tag

Demo: Highlighting text in a paragraph

5. Animated text effects

Simple yet powerful script to animate text properties. It yields some intersting results when combined with CSS3 transitions. This snippet is provided as a jQuery plugin for ease of use:

$.fn.animateText = function(delay, klass) {
  var text = this.text();
  var letters = text.split('');
  return this.each(function(){
    var $this = $(this);
    $this.html(text.replace(/./g, '<span class="letter">$&</span>'));
    $this.find('span.letter').each(function(i, el){
      setTimeout(function(){ $(el).addClass(klass); }, delay * i);

Create a class in CSS with some styles and run the plugin on an element that contains some raw text, like a paragraph.

$('p').animateText(15, 'foo');

Demo: Typewriter and highlighter effects with CSS3 transitions

6. Fading elements one by one

jQuery plugin to fade a collection of elements one by one with custom delay:

$.fn.fadeAll = function (ops) {
  var o = $.extend({
    delay: 500, // delay between elements
    speed: 500, // animation speed
    ease: 'swing' // other require easing plugin
  }, ops);
  var $el = this;
  for (var i=0, d=0, l=$el.length; i<l; i++, d+=o.delay) {
    $el.eq(i).delay(d).fadeIn(o.speed, o.ease);
  return $el;


$(elements).fadeAll({ delay: 300, speed: 300 });

Demo: Fading images one by one

7. Counting clicks

Sometimes you need to know how many times the user clicks on an element. The most common solution is to create a counter as a global variable but with jQuery you can prevent polluting the global scope by using data() to store the counter.

    .data('counter', 0) // begin counter at zero
    .click(function() {
        var counter = $(this).data('counter'); // get
        $(this).data('counter', counter + 1); // set
        // do something else...

Demo: Counting clicks on a button

8. Embedding Youtube videos from links

Useful script to create embedded Youtube videos from links with custom parameters. It works with mostly every Youtube link format since it uses a pretty forgiving regex, but it may not work for every single case. This script also fixes the tedious “super z-index” issue that you may have experienced when embedding Youtube videos.

function embedYoutube(link, ops) {

  var o = $.extend({
    width: 480,
    height: 320,
    params: ''
  }, ops);

  var id = /\?v\=(\w+)/.exec(link)[1];

  return '<iframe style="display: block;"'+
    ' class="youtube-video" type="text/html"'+
    ' width="' + o.width + '" height="' + o.height +
    ' "src="http://www.youtube.com/embed/' + id + '?' + o.params +
    '&amp;wmode=transparent" frameborder="0" />';

Check out the Youtube API parameters for more info on params.

  { params: 'theme=light&fs=0' }

Demo: Embedded Youtube videos from links

9. Reducing text by word limit

This script is similar to the excerpt function in WordPress. It allows you to truncate a string to a particular number of words and it adds ellipsis if necessary. It works with text that may have other inline tags such as strong or em or links.

function excerpt(str, nwords) {
  var words = str.split(' ');
  words.splice(nwords, words.length-1);
  return words.join(' ') + 
    (words.length !== str.split(' ').length ? '&hellip;' : '');

Demo: Easy “read more” with inline tags

10. Creating dynamic menus

Create any type of menu dynamically, like ordered lists, unordered lists, select dropdowns… It’s a very simple script with lots of potential.

function makeMenu(items, tags) {

  tags = tags || ['ul', 'li']; // default tags
  var parent = tags[0];
  var child = tags[1];

  var item, value = '';
  for (var i = 0, l = items.length; i < l; i++) {
    item = items[i];
    // Separate item and value if value is present
    if (/:/.test(item)) {
      item = items[i].split(':')[0];
      value = items[i].split(':')[1];
    // Wrap the item in tag
    items[i] = '<'+ child +' '+ 
      (value && 'value="'+value+'"') +'>'+ // add value if present
        item +'</'+ child +'>';

  return '<'+ parent +'>'+ items.join('') +'</'+ parent +'>';


// Dropdown select month
  ['January:JAN', 'February:FEB', 'March:MAR'], // item:value
  ['select', 'option']

// List of groceries
  ['Carrots', 'Lettuce', 'Tomatos', 'Milk'],
  ['ol', 'li']

Demo: Creating many types of menus


These snippets will hopefully bring something new based on experience and hours of fiddling that hasn’t been shared before, at least in this form and shape. They can be real timesavers in some situations or a great start for your next awesome plugin.

If you find this useful or want to share your own twist, please leave a comment below.



Iconfinder Coupon Code and Review

Iconfinder offers over 1.5 million beautiful icons for creative professionals to use in websites, apps, and printed publications. Whatever your project, you’re sure to find an icon or icon…

WP Engine Coupon

Considered by many to be the best managed hosting for WordPress out there, WP Engine offers superior technology and customer support in order to keep your WordPress sites secure…

InMotion Hosting Coupon Code

InMotion Hosting has been a top rated CNET hosting company for over 14 years so you know you’ll be getting good service and won’t be risking your hosting company…

SiteGround Coupon: 60% OFF

SiteGround offers a number of hosting solutions and services for including shared hosting, cloud hosting, dedicated servers, reseller hosting, enterprise hosting, and WordPress and Joomla specific hosting.