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){
    this.onerror=null;
    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)


$(function(){
    if( browser == "mobile" )
    {
        var h = $(window).height();
        var w = $(window).width();
        if(w<h){showMe()} else {hideMe()}
    }
});
$(window).on("orientationchange",function(){
  if( browser == "mobile" )
    {
          if(window.orientation != 0){ hideMe()
        }else {showMe()}
    }
}); 
function hideMe(){
    $(".hide").css({"visibility":"hidden"});
}
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.


// HTML
<div class="header">header</div>
<div class="body">sample</div>
<div class="footer">footer</div>
// JS
function newPage( goto ){
    var A = [];
// A[ PAGE, HEADER, FOOTER, BACK ];
    switch( goto ){
    // welcome screen
    case( 0 ):
    A.push(goto,'x','x',0);
    break;}
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.


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

// jQUERY
<script>
numCount = numNow = 5;
wait = numCount*1000;
$.wait = function(ms) {
    var defer = $.Deferred();
    kill = setTimeout(
        function(){defer.resolve();}
    ,ms);
    return defer;
};
$.wait(numCount*1000).then(function(){
    clearTimeout(kill);
    // maybe load a new page, next?
});
function countDown(){
    if(numNow > 0){
    $.wait(1000).then(function(){
        numNow--;
        $('#number').html(numNow);
        countDown();
    });
    } 
}
countDown(); // start the crazy
</script>
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.


// GOOGLE
googleKey = 'abc123';
googURL = 'https://spreadsheets.google.com/feeds/list/'+googleKey+'/od6/public/values?alt=json';

// Using JSONP
$.ajax({
    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 ) {
        // http://evolt.org/regexp_in_javascript/    
        i=0;
        l=response['feed']['entry'].length;
        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++ ){
                
                if(k<j-1){
                    txx = txt[k];
                    xxx = txt[k].split(/\s+/).pop(); 
                    if(k>0){
                        txt[k] = txx.replace(xxx,'').trim().slice(0,-1)+'","'+xxx+'"';
                    } else {
                        txt[k] = '"'+xxx+'"';
                    }
                    txt[k] +=':"';
                }else{
                    txt[k]+='"';
                };    
            }
            obj += '{ '+txt.join('')+' }';
            
            if(i<l-1){obj+=','}
        }
        obj +="]";
        jsonx = obj = $.parseJSON( obj );
        console.log( obj );
        
        ko.applyBindings(viewModel(jsonx));
    }
});