Skip to content

Instantly share code, notes, and snippets.

@akai
Last active September 26, 2015 19:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akai/1148683 to your computer and use it in GitHub Desktop.
Save akai/1148683 to your computer and use it in GitHub Desktop.
JavaScript Snippets

Load newest JQuery 1.x library from Google's CDN

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>

The Window Scroll Event

  • It's a very, very, bad idea to attach handlers to the window scroll event.
  • Always cache the selector queries that you're re-using.
var outerPane = $details.find(".details-pane-outer"),
    didScroll = false;
$(window).scroll(function() {
    didScroll = true;
});

setInterval(function() {
    if ( didScroll ) {
        didScroll = false;
        // Check your page position and then
        // Load in more results
    }
}, 250);

Define Array Literals With Empty Values

var foo = [,,,,, "derp"];

is more efficient than

var foo = [undefined, undefined, undefined, undefined, undefined, "derp"]

Get Mouse Position

function getMousePosition(e) {
  var posx = 0, posy = 0;
  if (!e) e = window.event;
  if (e.pageX || e.pageY) {
    posx = e.pageX;
    posy = e.pageY;
  } else if (e.clientX || e.clientY) {
    posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
    posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
  }
  return {x: posx,y: posy}
}

Set Selection Range

function setSelectionRange(input, selectionStart, selectionEnd) {
  if (input.setSelectionRange) {
    input.focus();
    input.setSelectionRange(selectionStart, selectionEnd);
  } else if (input.createTextRange) {
    var range = input.createTextRange();
    range.collapse(true);
    range.moveEnd('character', selectionEnd);
    range.moveStart('character', selectionStart);
    range.select();
  }
}

function setCaretToPos (input, pos) {
  setSelectionRange(input, pos, pos);
}

via Compile Compass into CSS

$.fn.selectRange = function(start, end) {
  return this.each(function() {
    if (this.setSelectionRange) {
      this.focus();
      this.setSelectionRange(start, end);
    } else if (this.createTextRange) {
      var range = this.createTextRange();
      range.collapse(true);
      range.moveEnd('character', end);
      range.moveStart('character', start);
      range.select();
    }
  });
};

JSON.stringify to pretty-print JSON

JSON.stringify({ foo: "lorem", bar: "ipsum" }, null, 4);

output:

{
    "foo": "lorem",
    "bar": "ipsum"
}

Using jQuery Deferreds with Animations

$.when($('div').animate({"opacity": "0"}, 1000)).done(function(){
    // animations are finished, run code
});

Internet Explorer detection.

function IE(version) {
  var b = document.createElement('b');
  b.innerHTML = '<!--[if IE ' + version + ']><br><![endif]-->';
  return !!b.getElementsByTagName('br').length;
}
var IE6 = IE(6), IE7 = IE(7);

Pad Zeros

function pad(v) {
  return ('0' + v).substr(-2);
}

pad(6)  // 06
pad(13) // 13

Array.without

function without(a, i) {
  return (i = a.indexOf(i), i == -1) ? a : a.slice(0, i).concat(a.slice(i + 1))
}

var arr = ['a','b','c','d','e'];
var newArray = without(arr,’c’);  // ['a','b','d','e']

JavaScript Performance MythBusters™

1. for loops

var arr = [];
var len=arr.length;

for (var i=0; i<len; i++) {
  worker();
}

2. using indexes ls.getItem[i] not keys ls.getItem('key')

var value = localStorage.getItem[i];

3. Regular expressions

var reContains = /(?:^| )foo(?: |$)/;
function storedRegExp(
  return reContains.test(node.className);
}

Add commas: 3304 -> 3,304

function addCommas(str) {
  var amount = new String(str);
  amount = amount.split('').reverse();

  var output = '';
  for ( var i = 0; i <= amount.length-1; i++ ){
    output = amount[i] + output;
    if ((i+1) % 3 == 0 && (amount.length-1) !== i)output = ',' + output;
  }
  return output;
}

Unescape HTML in JS

function htmlDecode(input){
  var e = document.createElement('div');
  e.innerHTML = input;
  return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}
htmlDecode("&lt;img src='myimage.jpg'&gt;"); 
// returns "<img src='myimage.jpg'>"

User Agent Selectors

var b = document.documentElement;
b.setAttribute('data-useragent',  navigator.userAgent);
b.setAttribute('data-platform', navigator.platform );
b.className += ((!!('ontouchstart' in window) || !!('onmsgesturechange' in window))?' touch':'');
html[data-useragent*='Chrome/13.0'] .nav{
  background:url(img/radial_grad.png) center bottom no-repeat;
}

Object.keys

;(function(win){
  var doc = win.document
    , i = Object.keys(doc.body.appendChild(doc.createElement("iframe")).contentWindow)
  return Object.keys(win).filter(function(a){return i.indexOf(a) == -1})
})(window)
@akai
Copy link
Author

akai commented Mar 13, 2014

FrameBuster ~

Make sure your site isn't being IFRAME'd.

if (top.location != self.location) {
    top.location = self.location.href;
}

@akai
Copy link
Author

akai commented May 26, 2014

Get Query Params as Object ~

jQuery.extend({
  getQueryParameters: function(str) {
    return (str || document.location.search).replace(/(^\?)/,'').split("&").map(function(n){return n = n.split("="),this[n[0]] = n[1],this}.bind({}))[0];
  }
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment