JavaScript & jQuery snippets

Patterns

Module Patterns Explained (source)

Anonymous Closures

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

$(document).ready

Fired when the HTML document is loaded and the DOM is ready, even if all the graphics haven’t loaded yet. Executes before $(window).load.

$(document).ready(function() {
// document is loaded and DOM is ready
alert("document is ready");
});

$(window).load

Fired when the complete page is fully loaded, including all frames, objects and images

$(window).load(function() {
// page is fully loaded, including all frames, objects and images
alert("window is loaded");
});

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 || [];

jQuery 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);

Add/remove class on a click

$( ‘#more-button’ ).on( ‘click’, function(e){
    e.preventDefault();
    if( ! $( ‘#more-button’ ).hasClass( ‘expanded’) ){
        $( ‘#more-button’).addClass( ‘expanded’ );
    }else{
        $( ‘#more-button’).removeClass( ‘expanded’ );
    }
});
});



// in separate calls

function onClick($){
if ( ! $( ‘#more-button’ ).hasClass( ‘expanded’) ){
    $( ‘#more-button’).addClass( ‘expanded’ );
}else{
     $( ‘#more-button’).removeClass( ‘expanded’ );

}
}jQuery( document ).ready(function($) {
$( ‘#more-button’ ).on( ‘click’, function(e){
    e.preventDefault();
    onClick($);
});
});

 

 

 

 
 
 
 
 
 
 
 
 
 

jQuery 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);
});

jQuery select Elements in the DOM

$("div#id .class")

jQuery add/remove Elements in the DOM (

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

jQuery add multiple attributes

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

jQuery edit attributes of Elements in the DOM

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

jQuery edit CSS of Elements in the DOM

$(div#id .class).css("property","value")
$(“#main-nav”).css(“display”, “none”);

Each element

$('p').each(function() { 
console.log($(this).text());
})

When close icon is clicked

$(".close").click( function() {
players.forEach(iterate);
});

When Escape key is pressed

$(document).keyup(function(e) {
    if (e.keyCode === 27) {
         players.forEach(iterate)
    }
});

On hover

$('#newsletterNotification input[type="submit"]').hover(function() {
    $(this).parent().parent().toggleClass('hovered');
});

$('.footer__newsletter input[type="submit"]').hover(function() {
    $(this).parent().parent().toggleClass('hovered');
})

Add listeners for various events taking place in the DOM

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

$(".sections a").click(function(e){
e.preventDefault();
var kra = $(this).attr("data-kra");
var index = $(this).attr('data-number');
console.log(kra + ' ' + index);
document.querySelector('#' + kra + index).scrollIntoView({behavior:'smooth'});
});

$("#show-more-chat").click(function () {
if ($('#show-more-chat').attr('aria-expanded') == 'true') {
$(this).text('More from Chat');
} else {
$(this).text('Close');
}
});

$('#mobileMenu .nav-link').click(function(){
mobileOffsetTag = $(this).attr('href');
$('html, body').animate({
scrollTop:$(mobileOffsetTag).offset().top - 95
}, 100);
});

// SCROLL

$(window).scroll(function () {
// fix for smaller screens
varwindowsize = $(window).width();
if (windowsize >= 1650) {
if ($(this).scrollTop() > 800) {
$('#main-nav').fadeIn(1000);
} else {
$('#main-nav').fadeOut(300);
}
}
// Hide main-nav on mobile
if (windowsize <= 1649) {
$("#main-nav").css("display", "none");
}
});
// HOVER
$(function() { $('input[type="submit"]').hover(function() { $(this).parent().parent().toggleClass('hovered'); }) });

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', '');

When using Foundation JS

$(document).foundation();
// when a dropdown field changes
$("#cf5_field_1").change(function() {
    var selectedValue = $(this).find(":selected").val();

    switch (selectedValue) {
        case "XXX":
           $('#li-5-5').html("Description");
        break;
        default:
            $('#li-5-5').html("Default description");
    }

})