3

JavaScript tricks!

over 8 years ago from , Senior UX and Product Designer

What are some of your favorite JS tricks out there?

7 comments

  • Mustafa Cetin, over 8 years ago

    .getElement("hocus").focus()

    5 points
  • Kyle ConradKyle Conrad, over 8 years ago (edited over 8 years ago )

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

    4 points
  • Adam ConradAdam Conrad, over 8 years ago

    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

    0 points
  • Mario GiambancoMario Giambanco, over 8 years ago

    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.

    0 points
  • Xavier HaniquautXavier Haniquaut, over 8 years ago (edited over 8 years ago )

    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('');

    `

    0 points
  • Johan van EckJohan van Eck, over 8 years ago (edited over 8 years ago )
    localStorage.setItem('test', 'Save this for later'); test = localStorage.getItem('test'); console.log(test); // 'Save this for later'

    localStorage is awesome!

    0 points
  • Chris JohnsonChris Johnson, over 8 years ago

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

    0 points