Skip to content

Instantly share code, notes, and snippets.

@burhanuddin7
Last active November 8, 2022 10:49
Show Gist options
  • Save burhanuddin7/43cf553905f6b4a5bea7b7662d2dc159 to your computer and use it in GitHub Desktop.
Save burhanuddin7/43cf553905f6b4a5bea7b7662d2dc159 to your computer and use it in GitHub Desktop.
Contains all the basic function stored in one file and accessed globally
var customLib = {
/**
* A native JS extend() function.
* https://gist.github.com/cferdinandi/4f8a0e17921c5b46e6c4
* Merge defaults with user options
* @private
* @param {Object} defaults Default settings
* @param {Object} options User options
* @returns {Object} Merged values of defaults and options
*/
extend: function (defaults, options, options2) {
var extended = {};
var prop;
for (prop in defaults) {
if (Object.prototype.hasOwnProperty.call(defaults, prop)) {
extended[prop] = defaults[prop];
}
}
for (prop in options) {
if (Object.prototype.hasOwnProperty.call(options, prop)) {
extended[prop] = options[prop];
}
}
if (options2) {
for (prop in options2) {
if (Object.prototype.hasOwnProperty.call(options2, prop)) {
extended[prop] = options2[prop];
}
}
}
return extended;
},
validURL: function (url) {
var pattern = new RegExp(
"^(https?:\\/\\/)?" + // protocol
"((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.?)+[a-z]{2,}|" + // domain name
"((\\d{1,3}\\.){3}\\d{1,3}))" + // ip (v4) address
"(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*" + //port
"(\\?[;&a-z\\d%_.~+=-]*)?" + // query string
"(\\#[-a-z\\d_]*)?$",
"i"
);
return pattern.test(url);
},
validEmail: function (email) {
return email.match(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,15})+$/);
},
validPhoneNo: function(phoneno) {
return phoneno.match(/^[+]?[\s./0-9]*[(]?[0-9]{1,4}[)]?[-\s./0-9]*$/g);
},
emailContainsNonLatinCharacters: function (email) {
var emailSplits = email.split('@');
if (emailSplits.length > 2) {
return true;
}
return !/^[a-zA-Z0-9.'+-_|~]*$/.test(emailSplits[0]) || !/^[a-zA-Z0-9.-]*$/.test(emailSplits[1]);
},
/**
* http://youmightnotneedjquery.com/
* Ajax method in JavaScript xhr request
*/
ajax: function (type, url, data, async, requestHeader, success, error, sendDataFormat, withCredentials) {
/**
* https://www.tutorialspoint.com/How-to-validate-URL-address-in-JavaScript
* Check if URL is valid.
*/
if (!this.validURL(url)) {
return false;
}
var request;
if (window.XMLHttpRequest) {
// code for Modern browsers
request = new XMLHttpRequest();
} else {
// code for older browsers
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.open(type, url, async);
if (requestHeader) {
Object.keys(requestHeader).forEach(function eachKey(key) {
request.setRequestHeader(key, requestHeader[key]);
});
}
// handle readystatechange event
request.onreadystatechange = function () {
// check readyState property
// 4 signifies DONE
// Not checking status below 200 because there is no action item for those error.
if (this.readyState === 4 || this.status >= 200) {
// req.status of 200 means success
if (this.status === 200) {
/**
* This will exceute the custom message or task on success based on form API response.
* In our case it will show the pop-up modal.
*/
success(request);
} else if (this.status >= 200) { // Not checking status below 200 because there is no action item for those error.
// handle request failure
error(request); // To add any custom error based on requirement
}
}
};
request.onerror = function () {
// There was a connection error of some sort
// Not checking status below 200 because there is no action item for those error.
if(request.status >= 200) {
var form_err =
"XHR not able to make connection with Error " + request.status + ": " + request.statusText;
console.error(form_err);
Sentry.captureException(form_err);
}
};
/**
* Convert form data in urlencoded format
*/
if (withCredentials) {
request.withCredentials = true;
}
//set utm tracking
//check api url only path
//ref: https://stackoverflow.com/questions/736513/how-do-i-parse-a-url-into-hostname-and-path-in-javascript
var parserLinkNode = document.createElement('a');
parserLinkNode.href = url;
if (typeof parserLinkNode.pathname !== 'undefined') {
checkURL = parserLinkNode.pathname;
if (checkURL.indexOf('Endpoint Name') !== -1 ) { // add endpoint api name for checking
var whiteListParams = [
'utm_source',
'utm_medium',
'utm_platform',
'utm_content',
'utm_campaign',
'utm_campaigncode',
'utm_term'
], paramsObj = window.location.search
.slice(1)
.split('&')
.map(function (p) {
return p.split('=');
})
.reduce(function (obj, pair) {
if (pair.length >= 2) {
obj[pair[0]] = pair[1];
}
return obj;
}, {});
// check white list params
Object.keys(paramsObj).forEach(function (key) {
if (whiteListParams.indexOf(key) > -1) {
data[key] = paramsObj[key];
}
});
}
}
if (!sendDataFormat) {
// When api response required content type : "application/x-www-form-urlencoded; charset=UTF-8"
var transformRequest = function (d) {
var str = [];
for (var p in d) {
if (d[p]) { // check for null values
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(d[p]));
}
}
return str.join("&");
};
request.send(transformRequest(data));
} else {
// When api response required content type : application/json
request.send(data);
}
},
/**
* Get IE version Number
* https://stackoverflow.com/questions/19999388/check-if-user-is-using-ie
*/
msieversion: function () {
var ua = window.navigator.userAgent,
msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
// If Internet Explorer, return version number
return parseInt(ua.substring(msie + 5, ua.indexOf(".", msie)));
} // If another browser, return 0
return false;
},
/*
* Scroll to element position
* https://gist.github.com/ravid7000/f54a37fd131a0b2e5ed190b6f58a1bc9
* scrollTo(element.scrollTop || 200, 400)
*/
scrollIt: function (to, duration) {
var element = document.scrollingElement,
start = (element && element.scrollTop) || window.pageYOffset,
change = to - start,
increment = 20,
currentTime = 0;
function easeInOutQuad(t, b, c, d) {
t /= d / 2;
if (t < 1) return (c / 2) * t * t + b;
t--;
return (-c / 2) * (t * (t - 2) - 1) + b;
}
//animation scroll
var animateScroll = function() {
currentTime += increment;
var val = easeInOutQuad(currentTime, start, change, duration);
window.scrollTo(0, val);
if (currentTime < duration) {
window.setTimeout(animateScroll, increment);
}
};
animateScroll();
},
uniqueID: function () {
// Math.random should be unique because of its seeding algorithm.
// Convert it to base 36 (numbers + letters), and grab the first 12 characters
// after the decimal.
return Math.random().toString(36).substr(2, 12);
},
getParameterByName: function(name, url) {
/*
* Get Query Params from JS because WPEngine remove utm_* and gclid from GET object.
* Ref : https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
*/
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return "";
return decodeURIComponent(results[2].replace(/\+/g, " "));
},
/**
* Check Valid JSON and return object if json valid
* @param {string} str
* @returns boolean
*/
JSONParse: function(str) {
try {
var o = JSON.parse(str);
if (o && typeof o === "object") {
return o;
}
}
catch (e) { }
return false;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment