Menu

JavaScript & jQuery snippets

April 13, 2017 - javascript

Patterns

Module Patterns Explained (source)

Anonymous Closures

(function () {
    // ... all vars and functions are in this scope only
    // still maintains access to all globals
}());

Global Import

(function ($, YAHOO) {
    // now have access to globals jQuery (as $) and YAHOO in this code
}(jQuery, YAHOO));

Module Export

var MODULE = (function () {
    var my = {},
        privateVariable = 1;

    function privateMethod() {
        // ...
    }

    my.moduleProperty = 1;
    my.moduleMethod = function () {
        // ...
    };

    return my;
}());

Sub-module

MODULE.sub = (function () {
    var my = {};
    // ...

    return my;
}());

Object length

var length = Object.keys(playlists).length; 
for (var i = 0; i < Object.keys(playlists).length; i++) {
   //  do something
}

Array length

var length = playlists.length;

forEach Array in variable

ytPlayer.forEach(function (playlist, index) {
    console.log(playlist);
});

or

ytPlayer.forEach((playlist, index) => console.log(playlist));

Check if object, variable exists and assign it a new object if it doesn’t

if (!this.JSON) {
    this.JSON = {};
}
var MYAPP = MYAPP || {};
var playlists = window.playlists || [];

Add and remove class

$('#' + self.name + ' .progress-bar-hover').removeClass('over');
$('#' + self.name + ' .progress-bar-hover').addClass('over');

jQuery add CSS to an element

// HIDE THE VIDEO WITH  JS
$('#player_' + playlistName)
            .css({
                'position': 'absolute',
                'top': -500 + 'px',
                'left': -500 + 'px'
});

$('#' + self.name + ' .progress-bar-marker[data-index=' + index + ']').css('left', position);

index of a clicked button

$('.btn-default').click(function(){
    var index = $(this).parent().index();
});

$('#' + self.name + ' .play').on('click', function () {
     var index = $('.ytPlayer .play').index(this);
});

Select Elements in the DOM

$("div#id .class")

Add/Remove Elements in the DOM (

$("div#id .class").remove()

Add multiple attributes

$('#' + playlist.name)
    .attr({
        'data-name': playlist.name,
        'data-playlistId': playlist.playlistId,
        'class': 'ytPlayer'
});

Edit Attributes of Elements in the DOM

$(div#id .class).height("30px")

Edit CSS of Elements in the DOM

$(div#id .class).css("property","value")

Add listeners for various events taking place in the DOM

$(div#id .class).click(callback)

characters

var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

Get width and height

this.width = opt.width || window.getComputedStyle(this.container).width.replace('px', '');
this.height = opt.height || window.getComputedStyle(this.container).height.replace('px', '');