You know, that JavaScript hack you found online that you keep in your records like a well worn recipe card. The one that does the thing, or solves that problem. Share it here. Let's swap recipes!
It's not the world's most powerful piece of code, but I think I like this one the most...
// Takes DOM element, returns boolean
// tests if element's text has been truncated
function isTruncated(el) {
return (el.scrollWidth > el.clientWidth);
}
(I got this from Jason Berry: http://output.jsbin.com/ulajif/2)
Couple of reasons I like this:
Get a random number:
var random = (min, max) => {
if (!min || min < 0) {
min = 0;
}
if (!max) {
max = 9007199254740991;
}
if (min === max) {
return max;
}
if (min > max) {
min = Math.min(min, max);
max = Math.max(min, max);
}
let offset = min;
let range = max - min + 1;
let rd = Math.floor(Math.random() * range) + offset;
return rd;
};
Get relative time:
var relativize = (input) => {
let t = input instanceof Date ? input : new Date(input);
let delta = new Date() - t;
let nowThreshold = parseInt(t, 10);
if (isNaN(nowThreshold)) {
nowThreshold = 0;
}
if (delta <= nowThreshold) {
return 'Just now';
}
let units = null;
let conversions = {
millisecond: 1,
second: 1000,
minute: 60,
hour: 60,
day: 24,
month: 30,
year: 12
};
for (let key in conversions) {
if (delta < conversions[key]) {
break;
} else {
units = key;
delta /= conversions[key];
}
}
delta = Math.floor(delta);
if (delta !== 1) {
units += 's';
}
return [delta, units].join(' ') + ' ago';
};
I have a few I always use in my applications these days. Cloning things is something I find myself doing routinely in single page applications and comparing values. I could list way more, but I stopped at three, it was hard just choosing one.
Cloning an array:
function cloneArray(array) {
return array.slice();
}
Cloning an object:
function cloneObject(obj) {
return JSON.parse(JSON.stringify(obj));
}
Object comparison:
For comparing if two objects are the same. Loops through and checks if their properties match, their lengths and so on.
function objectIsEqual(a, b) {
var aProps = Object.keys(a);
var bProps = Object.keys(b);
if (aProps.length !== bProps.length) {
return false;
}
for (let i = 0; i < aProps.length; i++) {
var propName = aProps[i];
if (a[propName] !== b[propName]) {
return false;
}
}
return true;
}
if i have to pick ... this is one of the most often used in my career :D .... (copied from stackoverflow ofc....)
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
Returns an object with information about the viewport for some responsive JavaScript goodness:
function getViewport(){
this.w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
this.h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
this.output = {
w: this.w,
h: this.h,
orientation: this.w < this.h ? "portrait" : "landscape"
};
return this.output;
}
I have more than a few... But here is one I like to reference: (super auto complete!)
for(i=0; i<wordarr.length; i++){
// As I am typing words into a textbox, I loop through a list of saved values so that (character by character) if the letters (in sequence) is contained in any word in my stored list; add to a clickable container; The clicked/selected item appears/copies into the textbox I am/was typing in:
if(wordarr[i].indexOf(text.toLowerCase())>=0){
autocomplete.innerHTML = autocomplete.innerHTML+"<a href='#' onclick=\"setText('"+wordarr[i]+"')\">"+wordarr[i]+"</a>"+"<br />";
};`
}
Switches off all the remote stylesheets, so you can see how you page looks with only inlined CSS.
(function() {
var styles = document.querySelectorAll('link[rel=\'stylesheet\']');
for (var s = 0; s < styles.length; s++) {
styles[s].mediax = styles[s].media;
if (styles[s].media === 'only x') {
styles[s].media = styles[s].mediax;
} else if (styles[s].media !== 'print') {
styles[s].media = 'only x';
}
}
})();
I wouldn't call the following my favourite snippet; but one that came to my mind after I read your question. So might as well share it here. :) When I am building something simple, and want globally-unique identifiers for my objects, the following function does it for me.
function createGUID() {
function S4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4();
}
var guid = createGUID();
Christian Wattengård
c# js node <insert new cool thing here>
<sarc> var that = this; </sarc>