JavaScript tricks!
over 8 years ago from Dani Sanchez, Senior UX and Product Designer
What are some of your favorite JS tricks out there?
over 8 years ago from Dani Sanchez, Senior UX and Product Designer
What are some of your favorite JS tricks out there?
.getElement("hocus").focus()
A little hacky, but one of my favorites - as a designer, I hate widows (single words just hanging out on a line), so I use this in a lot of sites to prevent that:
$('h1, h2, h3, li, p, figcaption').each(function() { $(this).html($(this).html().replace(/\s((?=(([\s<>]|<[>]>)+))\2)\s$/,' $1')); });
Use !!
to test for boolean existence is a neat one.
Also just the general functional programming Array functions are pretty cool, so while most people know the common ones (map
, reduce
, filter
, forEach
) there are a bunch of more obscure ones as well that are really useful, such as some
, every
and reduceRight
function log(mess) { if(window.console) { console.log(mess); } }
Outputting to the console without it being open / visible will crash the execution of Javascript on older versions of IE. This prevents that.
I like this little trick to check the emptyness of a string :
`
var string = ""; console.log(!!string) //return false
`
and this other one for multiline string :
`
var multilineString = [ '<div>', '<span></span>', '</div> ].join('');
`
localStorage.setItem('test', 'Save this for later'); test = localStorage.getItem('test'); console.log(test); // 'Save this for later'
localStorage is awesome!
var object = { foo: true, bar: false, nested: { foobar: true } };
// Expandable Object console.log(object); // Raw string of Object console.log(JSON.stringify(object)); // Pretty String of Object console.log(JSON.stringify(object, 0, 2));
Designer News
Where the design community meets.
Designer News is a large, global community of people working or interested in design and technology.
Have feedback?
Login to Comment
You'll need to log in before you can leave a comment.
LoginRegister Today
New accounts can leave comments immediately, and gain full permissions after one week.
Register now