array(2) { ["meta"]=> array(6) { ["name"]=> string(10) "openaq-api" ["license"]=> string(0) "" ["website"]=> string(1) "/" ["page"]=> int(1) ["limit"]=> int(100) ["found"]=> int(0) } ["results"]=> array(0) { } } object(stdClass)#2 (13) { ["coord"]=> object(stdClass)#1 (2) { ["lon"]=> float(125.6081) ["lat"]=> float(9.0125) } ["weather"]=> array(1) { [0]=> object(stdClass)#3 (4) { ["id"]=> int(802) ["main"]=> string(6) "Clouds" ["description"]=> string(16) "scattered clouds" ["icon"]=> string(3) "03d" } } ["base"]=> string(8) "stations" ["main"]=> object(stdClass)#4 (8) { ["temp"]=> float(84.36) ["feels_like"]=> float(93.81) ["temp_min"]=> float(84.36) ["temp_max"]=> float(84.36) ["pressure"]=> int(1013) ["humidity"]=> int(77) ["sea_level"]=> int(1013) ["grnd_level"]=> int(1011) } ["visibility"]=> int(10000) ["wind"]=> object(stdClass)#5 (3) { ["speed"]=> float(2.26) ["deg"]=> int(92) ["gust"]=> float(4.83) } ["clouds"]=> object(stdClass)#6 (1) { ["all"]=> int(41) } ["dt"]=> int(1711687321) ["sys"]=> object(stdClass)#7 (3) { ["country"]=> string(2) "PH" ["sunrise"]=> int(1711661800) ["sunset"]=> int(1711705664) } ["timezone"]=> int(28800) ["id"]=> int(1705545) ["name"]=> string(11) "Los Angeles" ["cod"]=> int(200) } DrPunchman

Code Bites JS

Image not found

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.


ImgNotFound.js


// 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)


MobileDetection.js


$(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.


LoadPage2Div.js


// 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.


CountDown2Load.js


// 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.


BadJson.js


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