JavaScript - jQuery

A collection of useful jQuery code snippets

// get the value of a text input when modified
(function($){
    $('#sometextinput').on('change keyup paste', function() {
        console.log('VALUE', $(this).val());
    });
})(jQuery);

Window Resize

Wait for window resize to stop.

var resizeTimeout;
$(window).on('resize', function() {
    clearTimeout(resizeTimeout);
    resizeTimeout = setTimeout(doSomething(), 500);
});

If LoDash is present, you can use _.debounce instead.

$(window).on('resize', _.debounce(doSomething, 150));

with jQuery.proxy

$(window).on('resize', _.debounce( $.proxy( function() {
   // code
}, this), 150));

Vanilla JS Resize Handler

jQuery.extend

Use $.extend to merge objects.

var data = $.extend({}, {
    'artist': 'Ben Harper',
    'track': 'Gold To Me'},
    album, discography);

If LoDash is present, use _.extend instead.

var data = {
    'artist': 'Ben Harper',
    'track': 'Gold To Me'}

_.extend(data, album, discography);
jQuery.proxy

Use $.proxy on $.ajax callback to access this from lower scope

fetchData () {
    this.error = this.posts = null

    this.loading = true

    $.ajax({
        url: https://wordpress.example.com + '/wp/v2/posts'
    })
    .done( $.proxy( function( response ) {

        this.loading = false;
        this.posts = response;

    }, this ))
    .fail( $.proxy( function( response ) {

        this.loading = false;
        this.error = response;

    }, this ));
}

Various Ajax Error Responses

Use .ajaxSetup to add more precise ajax error handling.

$.ajaxSetup({
    error: function(jqXHR, exception) {
        if (jqXHR.status === 0) {
            alert('Not connect.\n Verify Network.');
        } else if (jqXHR.status == 404) {
            alert('Requested page not found. [404]');
        } else if (jqXHR.status == 500) {
            alert('Internal Server Error [500].');
        } else if (exception === 'parsererror') {
            alert('Requested JSON parse failed.');
        } else if (exception === 'timeout') {
            alert('Time out error.');
        } else if (exception === 'abort') {
            alert('Ajax request aborted.');
        } else {
            alert('Uncaught Error.\n' + jqXHR.responseText);
        }
    }
});

WordPress

// sticky header and footer
jQuery.noConflict();
    (function($) {
        // wait for resize to stop
        var resizeTimeout;
        $(window).on('resize', function() {
            clearTimeout(resizeTimeout);
            resizeTimeout = setTimeout(setContentHeight, 500);
        });
        setContentHeight = function(event) {
            cVerticalMargin = $('.site-content').outerHeight(true)
                - $('.site-content').outerHeight();
            cVerticalBorder = $('.site-content').outerHeight()
                - $('.site-content').innerHeight();
            cVerticalPadding = $('.site-content').innerHeight()
                - $('.site-content').height();
            cHeight = $(window).height()
                - $('.site-header').outerHeight(true)
                - $('.site-footer').outerHeight(true)
                - cVerticalMargin
                - cVerticalBorder
                - cVerticalPadding;
            $('.site-content').css({'height': cHeight + 'px'});
        }
        setContentHeight();
})(jQuery);

Supporting Older and Newer jQuery

If you find yourself in a messy situation where you need to provide support for jQuery earlier than 1.7 on an intermittent basis.

// for those who use jquery earlier then 1.7 when there is no $.on exist yet
if (typeof jQuery.fn.on !== 'function') {
    jQuery.fn.on = jQuery.fn.live;
    jQuery.fn.off = jQuery.fn.die;
}