getButterfly Logo getButterfly

Here is a collection of random jQuery code snippets, created during various past projects. Note that they require the jQuery library and some require various CSS classes and/or a certain HTML structure.

1. Count DOM elements and display the total value. Use for a list of results.

var mycount = $('.element').length;
$(".results").text(mycount);

2. Pad digits when you need to display numbers as 01, 02, 03 … 10, 11, 12, 13 … 99:

function padDigits(number, digits) {
    return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
}

3. Remove duplicate elements (<option>) of a <select> dropdown:

function removeSelectDuplicates($element) {
    var found = [];

    $($element + " option").each(function() {
        if($.inArray(this.value, found) != -1)
            $(this).remove();
        found.push(this.value);
    });
}

4. Sort elements (<option>) of a <select> dropdown, based on name (alphabetically):

function sortSelectA($element) {
    $($element).html($($element + ' option').sort(function(x, y) {
        return $(x).val() < $(y).val() ? -1 : 1;
    }));

    $($element).get(0).selectedIndex = 0;
}

5. Set/get cookies:

function setCookie(name, value, days) {
    var expires = "";

    if (days) {
        var date = new Date();

        date.setDate(date.getDate() + days);
        expires = "; expires=" + date.toGMTString();
    }

    document.cookie = name + "=" + escape(value) + expires + "; path=/;";
}

function getCookie(name) {
    var dc = document.cookie;
    var begin = dc.indexOf(name);

    if (begin == -1) {
        return "";
    }

    var end = (dc.indexOf(";", begin) == -1) ? dc.length : dc.indexOf(";", begin);

    return unescape(dc.substring((begin + (name.length + 1)), end));
}

6. Use the cookie functions above to set cookies based on an input element:

function setCustomCookie(type) {
    if(type == 'your-type-here') {
        setCookie('campaign', jQuery('#element').val(), 30);
    }
}

7. Highlight active menu item:

var url = location.protocol + '//' + location.host + location.pathname;

$('ul.navigation li').children('a').each(function(){
    if(this.href == url) {
        $(this).parent().addClass('active');
    } else {
        $(this).parent().removeClass('active');
    }
});

8. Send Google Analytics event on element click (requires Google Universal tracking code):

$(document).on('click', '.element', function() {
    // get a value from the element's data attribute
    var data_tracker = $(this).parent().attr('data-tracker');

    ga('send', {
        hitType: 'event',
        eventCategory: 'Your Category Here',
        eventAction: 'Click',
        eventLabel: data_tracker
    });
});

9. Get URL parameters:

var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = decodeURIComponent(window.location.search.substring(1)),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : sParameterName[1];
        }
    }
};

var sort = getUrlParameter('your-parameter-1');
var range = getUrlParameter('your-parameter-2');

10. Animate expanding height of a textarea element on focus and collapsing it when clicking a button:

$("textarea").focus(function(){
    $(this).animate({"height": "300px",}, "fast");

    return false;
});
$("#close").click(function(){
    $("textarea").animate({"height": "20px",}, "fast");

    return false;
});

11. Text-only tooltip based on the title attribute:

$('.hasTooltip').hover(function() {
    var title = $(this).attr('title');

    $(this).data('tipText', title).removeAttr('title');
    $('<p class="tooltip"></p>').text(title).appendTo('body').fadeIn('slow');
}, function() {
    $(this).attr('title', $(this).data('tipText'));
    $('.tooltip').remove();
}).mousemove(function(e) {
    var mousex = e.pageX + 20;
    var mousey = e.pageY + 10;
    $('.tooltip').css({ top: mousey, left: mousex })
});

12. Zebra table with one jQuery line:

$('table tr:odd').addClass('odd');

Enjoy!


Subscribe to getButterfly Blog

Once a week or so we send an email with our best content. We never bug you, we just send you our latest piece of content.



If you found any value in this post, agree, disagree, or have anything to add - please do. I use comments as my #1 signal for what to write about. Read our comment policy before commenting! Comments such as "Thank you!", "Awesome!", "You're the man!" are either marked as spam or stripped from URL.

Leave a Reply

Your email address will not be published. Required fields are marked *