Random javascript tricks

2 years ago | #Javascript #Snippet

Here are some JS tricks that I had stuck in a .txt on my desktop for quite a while. Since I’m doing a spring clean, I’d better post them here so I don’t forget about them!

Some might not be particularly good for usage with teams (unless you all know about them of course), but it’s interesting nonetheless to know that these exist.

Script tag templating

You can stick pretty much anything in a script tag with type=’text’.

<script type="text" id="template">
<h1>This won't display</h1>
</script>

You can then retrieve it later with a simple query:

var text = document.getElementById('template').innerHTML

Make any element editable

contentEditable attribute makes any dom node editable

Typing this onto the console allows you to edit the page like in a text editor.

document.body.contentEditable = 'true';
document.designMode = 'on';

Function ‘chaining’

if (confirm('Do you wish to see two alerts?'))
    alert(1), alert(2);

Bitwise integer math

Javascript doesn’t have an Integer type, but you can use bitwise operators to perform Integer math:

var foo = (12.4 / 4.13) | 0; // Math.round()
var bar = ~~(12.4 / 4.13); // also 0|(12.4 / 4.13) // Math.floor()

Easy parseInt

Unary operator, which converts a string to a number, shorter and faster than parseInt

+'55' == 55 // => true

Variable swapping

Use an array to swap variables

// Before
var a = 1, b = 2, c;
c = a;
a = b;
b = c;

// After
var a = 1, b = 2;
a = [b, b = a][0]

IE detection

// Detect any IE version
var IE = !+'\v1';

// or
var IE = !-[1, ];

// or detect specific versions
var IE = (function(){
    var undef,
          v = 3,
          div = document.createElement('div'),
          all = div.getElementsByTagName('i');

    while (
        div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
        all[0]
    );

    return v > 4 ? v : undef;
}());
console.log(IE < 9);

Cleaner Array.indexOf check

var arr = ['a', 'b', 'c'];
if (~(arr.indexOf('a')) {
    console.log('Value 'a' is present in arr');
}