Check if object properties exist

var pets = { 
  "cats": { 
    "persian": {
      "black": 1,
      "white": 2,
    }, 
    "sphynx": {
      "blue": 2,
      "white": 2,
    }
  },
  "dogs": {
    "pug": {
      "black": 1,
      "brown": 2,
      "white": 1,
    },
    "bulldog": {
      "brown": 1,
      "white": 1,
    }
  }
}
if(pets.persian.black){
  //This might throw an exception if persian does not exist. Error: black of undefined
}

 

Solution with lodash:

_.get(pets, ‘persian.black’)

Clone a nested Object

When we assign a nested object to a new property, the properties nested inside the object will remain linked. In some cases we can use the spread operator to create a whole new object but this will only work with 1 level of nested objects. In order to have a complete new instance of the object with no reference to the original object, we can use lodash _.cloneDeep() method.

Requirements: lodash

Examples:

var test = {
  user: {
    name: 'Roch',
    surname: 'Cassar',
    education: {
      primary: {},
      secondary: {},
      tertiary: {}
    }
  }
};

I can use the spread operator to get a new instance of user as follows:

var newUser = {...test.user};

The problem is that education will not be cloned but will still be referenced. To Avoid this, we can use cloneDeep by lodash.

var newUser = _.cloneDeep(test.user);

 

 

 

 

Calculate Age in JavaScript

HTML:

<input type="date" id="DOB" name="DOB" />

 

 JAVASCRIPT in SCRIPT tags:

//Since new Date() created a date in the format mm/dd/yyyy, we need to format our dob to match the same format
var dob_formatted = switchMonthDate(document.getElementById(“DOB”).value);

//Calculate Age
//Subtract dob from today's date and divide by total milliseconds in a year
var age = Math.floor((new Date() - dob_formatted)/ 31536000000);


if(age >= 18)
{

console.log("adult");

}


function switchMonthDate(dateFirst)
{


if(dateFirst.indexOf("/") !== -1)
dateFirst=dateFirst.split("/");
else if(dateFirst.indexOf("-") !== -1)
dateFirst=dateFirst.split("-");
else if(dateFirst.indexOf(".") !== -1)
dateFirst=dateFirst.split(".");
var monthFirst=dateFirst[1]+"/"+dateFirst[0]+"/"+dateFirst[2];


return new Date(monthFirst);


}

 

 

Change iFrame Height according to iFrame content (no jQuery required)

In the Parent page (which references the iframe), include the following in a script tag within your head section of your html:

if (window.addEventListener) {
addEventListener(“message”, messageListener, false)
} else if (window.attachEvent) {
attachEvent(“onmessage”, messageListener)
}
function messageListener(event) {
var originSecure = event.origin === “http://myiframe.com ” ;
if (!originSecure)
return;

if (parseInt(event.data) > 0)
document.getElementById(“test”).style.height = event.data + “px”;
}

 

Meanwhile, in your iframe include the following post message in your document ready script:

parent.postMessage(window.innerHeight, “*”);

Bootstrap fallback helper for IE8

Bootstrap has its own fallbacks for old browsers, but I was never fully satisfied with the result. The following helps setting the basic elements in place:

  1. First add a JavaScript function to check if IE and if IE get the version

function isIE() {
var myNav = navigator.userAgent.toLowerCase();
return (myNav.indexOf(‘msie’) != -1) ? parseInt(myNav.split(‘msie’)[1]) : false;
}

 

  1. On document load detect if IE and if version 8, append fallback classes to the head section of the page:

$(document).ready( function () {
if (isIE () == 8) {
$(“head”).append(“” +
“.container { width: 1170px; max-width: 1170px; min-widt: 1170px; } ” +
“.col-xs-1,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9,.col-xs-10,.col-xs-11,.col-xs-12,.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12,.col-md-1,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-md-10,.col-md-11,.col-md-12,.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11,.col-lg-12{float:left}” +
“.col-xs-1, .col-sm-1, .col-md-1, .col-lg-1 { width: 8%; }.col-xs-2, .col-sm-2, .col-md-2, .col-lg-2 { width: 16%; }.col-xs-3, .col-sm-3, .col-md-3, .col-lg-3 { width: 25%; }.col-xs-4, .col-sm-4, .col-md-4, .col-lg-4 { width: 33%; }.col-xs-5, .col-sm-5, .col-md-5, .col-lg-5 { width: 41%; }.col-xs-6, .col-sm-6, .col-md-6, .col-lg-6 { width: 50%; }.col-xs-7, .col-sm-7, .col-md-7, .col-lg-7 { width: 58%; }.col-xs-8, .col-sm-8, .col-md-8, .col-lg-8 { width: 66%; }.col-xs-9, .col-sm-9, .col-md-9, .col-lg-9 { width: 75%; }.col-xs-10, .col-sm-10, .col-md-10, .col-lg-10 { width: 83%; }.col-xs-11, .col-sm-11, .col-md-11, .col-lg-11 { width: 91%; }.col-xs-12, .col-sm-12, .col-md-12, .col-lg-12 { width: 100%; }” +
“.col-sm-2 { width: 160px; margin:0; padding:0; float: left; }.col-sm-10 { width: 670px; margin:0; padding:0; float: left; }.col-md-12 { width: 100%; margin:0; padding:0; float: left; }.col-md-6 { width: 450px; margin-left: 10px;}.divider { height: 560px; }” +
“.hidden-xs, .hidden-sm, .hidden-md, .hidden-lg { display:block;}” +
“”);

}
});

Mobile, iOS, Safari, IE browser detection using simple JS

This post is just for reference for when browser detections are required:


/*If handheld device such as mobile and tablets returns true, else false */
function isHandheldDevice() {
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)){
return true;
}
return false;
}


/*Simple: If safari on windows returns true, else false */
function isSafariOnWindows() {
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf("safari/") !== -1 && // It says it's Safari
ua.indexOf("windows") !== -1 && // It says it's on Windows
ua.indexOf("chrom") === -1 // It DOESN'T say it's Chrome/Chromium
) {
return true;
}
return false;
}


/*Advanced: If safari on windows returns true, else false */
function isSafariNotMac () {
var myNav = navigator.userAgent.toLowerCase();
var is_chrome = myNav.indexOf('chrome') > -1;
var is_safari = myNav.indexOf("safari") > -1;
var is_mac = myNav.indexOf("macintosh") > -1;
var is_windows = myNav.indexOf("windows") > -1;
if ((is_chrome)&&(is_safari)) {is_safari=false;}
if ((is_mac)&&(is_safari)) {is_safari=false;}
if ((is_windows)&&(is_safari)) {is_safari=false;}
return is_safari;
}


/* If Safari return version number, else return false */
function safariVersion()
{
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf("safari/") !== -1 && ua.indexOf("chrom")   === -1 )
{
var version = parseInt(ua.substr(ua.indexOf("safari/") + ("safari/").length, 1));
return version;
}
return false;
}


/* If IE return version number, else return false */
function isIE() {
var myNav = navigator.userAgent.toLowerCase();
return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
}

How to check if user is on handheld device (mobile/tablet) using JavaScript

Just Paste the code below and call isHandheldDevice() when you would like to know. True would mean the user is on a mobile or tablet.

<script>
function isHandheldDevice() {
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))
return true;

return false;
}
</script>

Image Not Found Solution

It is very annoying when missing images are shown as the default broken image as it is first of all, ugly, and secondly sometimes destorts the height/width of your content. This is a very quick and easy solution:

<img src=”myImage.jpg” onerror=”this.src=’no-image-found.jpg’;” alt=”My Image”/>

Knockout.js Script1028 – Expected identifier string or number (in IE8)

Issue:

Have been developing an app which uses knockout js. All seemed to work fine until I tried to test on IE8. I kept on getting an error “Script1028 – Expected identifier string or number”.

Possible Causes and Solutions:

  1. When binding using knockout js, make sure that there are no trailing commas at the end of the data-bind such as: data-bind=” text: ‘click me’, attr:{href: ‘www.rochcass.com’},
  2. When binding a javascript reserved word, such as “this, if, class”, make sure to stringify that specific reserved word. For a full list of reserved word, click here

Just an FYI, my solution was number 2, I had a data-bind=” class: ‘sampleClass’ “ and since class is a javascript reserved word this had to be written as data-bind=” ‘class’: ‘sampleClass’ “.

Hope this helped 🙂

 


It’s Not a Typo! Get $1.49 .COM Domains at GoDaddy!