Tutorial Get URL Variables

by in , 0

function getQueryVariable(variable)
{
       var query = window.location.search.substring(1);
       var vars = query.split("&");
       for (var i=0;i<vars.length;i++) {
               var pair = vars[i].split("=");
               if(pair[0] == variable){return pair[1];}
       }
       return(false);
}

Usage

Example URL:

http://www.example.com/index.php?id=1&image=awesome.jpg

Calling getQueryVariable("id") - would return "1".
Calling getQueryVariable("image") - would return "awesome.jpg".

Tutorial Get URL and URL Parts in JavaScript

by in , 0

JavaScript can access the current URL in parts. For this URL:

http://css-tricks.com/example/index.html

window.location.protocol = "http" window.location.host = "css-tricks.com" window.location.pathname = "example/index.html"

So to get the full URL path in JavaScript:

var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;

If you need to breath up the pathname, for example a URL like http://css-tricks.com/blah/blah/blah/index.html, you can split the string on "/" characters

var pathArray = window.location.pathname.split( '/' );

Then access the different parts by the parts of the array, like

var secondLevelLocation = pathArray[0];

To put that pathname back together, you can stitch together the array and put the "/"'s back in:

var newPathname = "";
for ( i = 0; i < pathArray.length; i++ ) {
  newPathname += "/";
  newPathname += pathArray[i];
}

Tutorial Get Object Size

by in , 0

As in, the number of keys.

function objectSize(the_object) {
  /* function to validate the existence of each key in the object to get the number of valid keys. */
  var object_size = 0;
  for (key in the_object){
    if (the_object.hasOwnProperty(key)) {
      object_size++;
    }
  }
  return object_size;
}

Usage

// Arbitrary object
var something = {
  dog: "cat",
  cat: "dog"
}

console.log(objectSize(something));
// Logs: 2

Tutorial Get All Possible DOM Events

by in , 0

You can get an array of all the events that start with "on" (e.g. onclick) by running this in the Console of Firefox.

[i for(i in document)].filter(function(i){return i.substring(0,2)=='on'&&(document[i]==null||typeof document[i]=='function');})

You'll get an array like this (Firefox 23):

["onreadystatechange", "onmouseenter", "onmouseleave", "onwheel", "oncopy", "oncut", "onpaste", "onbeforescriptexecute", "onafterscriptexecute", "onabort", "oncanplay", "oncanplaythrough", "onchange", "onclick", "oncontextmenu", "ondblclick", "ondrag", "ondragend", "ondragenter", "ondragleave", "ondragover", "ondragstart", "ondrop", "ondurationchange", "onemptied", "onended", "oninput", "oninvalid", "onkeydown", "onkeypress", "onkeyup", "onloadeddata", "onloadedmetadata", "onloadstart", "onmousedown", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onpause", "onplay", "onplaying", "onprogress", "onratechange", "onreset", "onseeked", "onseeking", "onselect", "onshow", "onstalled", "onsubmit", "onsuspend", "ontimeupdate", "onvolumechange", "onwaiting", "onmozfullscreenchange", "onmozfullscreenerror", "onmozpointerlockchange", "onmozpointerlockerror", "onblur", "onerror", "onfocus", "onload", "onscroll"]

Firefox, because it supports array comprehension which that little snippet uses.

Reference URL

Tutorial Format Currency

by in , 0

This function will round numbers to two decimal places, and ensure that the returned value has two decimal places. For example 12.006 will return 12.01, .3 will return 0.30, and 5 will return 5.00

function CurrencyFormatted(amount) {
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}

Tutorial Fix IE 10 on Windows Phone 8 Viewport

by in , 0

(function() {
  if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
    var msViewportStyle = document.createElement("style");
    msViewportStyle.appendChild(
      document.createTextNode("@-ms-viewport{width:auto!important}")
    );
    document.getElementsByTagName("head")[0].appendChild(msViewportStyle);
  }
})();

Quick backstory

For IE 10 (desktop) to work in it's new "snap mode" you need to use this:

@-ms-viewport {
  width: device-width;
}

But that screws up some Windows Phone 8 phones, overriding the meta viewport tag and rendering as far too large on small screens. So the answer, for now, is this gnarly device detection/injection script.

Longer backstory

Matt Stow: Responsive Design in IE10 on Windows Phone 8 Tim Kadlec: Windows Phone 8 and Device-Width

Tutorial Error-Free Console Logging

by in , 0

var Fb = {}; //An empty object literal for holding the function
Fb.log = function(obj, consoleMethod) {
       if (window.console && window.console.firebug && window.console.firebug.replace(/^\s\s*/, '').replace(/\s\s*$/, '') !== '') {
               if (typeof consoleMethod === "string" && typeof console[consoleMethod] === "function") {
                       console[consoleMethod](obj);
               } else {
                       console.log(obj);
               }
       }
}

If you leave console.log, console.info, etc messages in your JavaScript code and open the page in browser like IE then it may halt the page loading completely saying that 'console not defined' especially if your user uses a non IE8 browser.

This code snippet will allow you to leave the logging message as such in your code if you wish and your page will render properly in IE or any other browser that does not support the console messages.

Usage

Fb.log("This will be logged");

Fb.log("This will be displayed in console as info", "info");

The FB.log function accepts two parameters the first one is the "item" that you want to display in the firebug console and the second one is the firebug method that you want to use for the logging, like info, error, etc. If you omit the second parameter the result will be equivalent to console.log()

Simple log-only way

function ltc(what) {
       try {
               console.log(what);
       }
       catch (e) {}
       finally {
               return;
       }
}
ltc("message");