Code Bites JS

Some fun little nuggets of JavaScript
Fun with JavaScript

Here are some useful little code bites, I hope you enjoy.

Image not found

Code that loads another image when the one you want can’t be found. I will tell you, this one takes a little while to work because the browser really wants to load the right image so it takes a little while before it will quit.

// hard way
<img src="img.jpg" onError="imgFix(this)">
function imgFix(e){
    var src = $(e).attr('src');
    src = imgDir + src ;
    e.src = src;
// easy way
<img src="img.jpg" onError="this.src='default.jpg'">
Mobile Detection

Check to see if your site is on a mobile device. Sounds easy enough, right? Oh… I’m checking orientation too (landscape vs portrait)

    if( browser == "mobile" )
        var h = $(window).height();
        var w = $(window).width();
        if(w<h){showMe()} else {hideMe()}
  if( browser == "mobile" )
          if(window.orientation != 0){ hideMe()
        }else {showMe()}
function hideMe(){
function showMe(){
    $(".hide").css({"visibility":"visible"});// Landscape
Load Page into DIV

Sometimes, you just want to load things into a DIV tag, without all that hub-bub. Here is how I do it.
OK, so I do it with an array, but I love arrays, and tend to sneak them into everything. I can’t help it.

<div class="header">header</div>
<div class="body">sample</div>
<div class="footer">footer</div>
// JS
function newPage( goto ){
    var A = [];
    switch( goto ){
    // welcome screen
    case( 0 ):
PAGE =(A[0]=='x')?'404.html': 'page_'+A[0]+'.html';
    // repeat for all sections
    $('.header').load( HEADER );
    $('.body').load( PAGE );
    $('.footer').load(FOOTER );
Count Down to New Page

This is a little bit of code that I used for a demo, where I would play a gif for a few seconds before loading a page. I wanted a count down timer so that people knew they weren’t stuck watching a GIF forever.

<img src="ani.gif" width="100%" height="100%">
<div class="timeRemains">
[ Movie Ends in <span id="number">7</span> Sec ]

numCount = numNow = 5;
wait = numCount*1000;
$.wait = function(ms) {
    var defer = $.Deferred();
    kill = setTimeout(
    return defer;
    // maybe load a new page, next?
function countDown(){
    if(numNow > 0){
countDown(); // start the crazy
Re-formatting bad JSON

Google sent me some crap JSON like [{“cake:yummy,belt:tight,brown,leather,car:fast”}] it should look more like [{“cake”:”yummy”,”belt”:”tight,brown,leather”,”car”:”fast”}] even then, KnockOut.js wants it to look like: [{cake:”yummy”,belt:”tight,brown,leather”,car:”fast”}]… so this is how I fixed it.

googleKey = 'abc123';
googURL = ''+googleKey+'/od6/public/values?alt=json';

// Using JSONP
    url: googURL,
    // the name of the callback parameter, as specified by the YQL service
    jsonp: "callback",
    // tell jQuery we're expecting JSONP
    dataType: "jsonp",
    // work with the response
    success: function( response ) {
        obj = "[";    
        for( i;i<l;i++ ){
            txt = response['feed']['entry'][i]['content']['$t'];
            txt = txt.split(':');
            j = txt.length;
            for( k=0;k<j;k++ ){
                    txx = txt[k];
                    xxx = txt[k].split(/\s+/).pop(); 
                        txt[k] = txx.replace(xxx,'').trim().slice(0,-1)+'","'+xxx+'"';
                    } else {
                        txt[k] = '"'+xxx+'"';
                    txt[k] +=':"';
            obj += '{ '+txt.join('')+' }';
        obj +="]";
        jsonx = obj = $.parseJSON( obj );
        console.log( obj );