Last Updated: February 25, 2016
·
1.195K
· idered

Functions & Tenary operaions

Nothing to describe here, just take a look at examples and you'll love this technique.

Target: hide sidebar when window width is less than 800px.

#1 - Lame

$(window).on('resize', function() {
    if($(this).width() > 800) {
        $('#sidebar').show();
    } else {
        $('#sidebar').hide();
    }
}).trigger('resize');

#2 - Ain't bad

$(window).on('resize', function() {
    $(this).width() > 800 ? $('#sidebar').show() : $('#sidebar').hide();
}).trigger('resize');

#3 - Like a boss

$(window).on('resize', function() {
    $('#sidebar')[$(this).width() > 800 ? 'show' : 'hide']();
}).trigger('resize');

As you see, the 3rd technice is the cleanest one and 100% valid. Now go and start coding like a boss.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside