Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Is there a better way to write this simple script?

Hey guys, I wrote this but I'm guessing that there is a better way to do it, right?

$(document).ready(function(){
$(".nav-events").click(function () {
    $(".events").css('display', 'block');
    $(this).addClass("active");
    $(".news").css('display', 'none');
    $(".nav-news").removeClass("active");

});
});

$(document).ready(function(){
$(".nav-news").click(function () {
    $(".news").css('display', 'block');
    $(this).addClass("active");
    $(".events").css('display', 'none');
    $(".nav-events").removeClass("active");
});
});

1 Answer

"Better" is quite a subjective term. You should write it in a way that will make sense to you and future developers.

That being said there is some redundancy in your code. A different way of writing this could be:

$(document).ready(function(){
    $(".nav-events").on('click', function () {
        $(".events").show();
        $(this).addClass("active");
        $(".news").hide();
        $(".nav-news").removeClass("active");

    });

    $(".nav-news").on('click', function () {
        $(".news").show();
        $(this).addClass("active");
        $(".events").hide();
        $(".nav-events").removeClass("active");
    });
});

You don't need to put each block in it's own ready handler, one is enough and jQuery already has methods for hiding and showing elements $(el).show() and $(el).hide().

The only real problem with your code above is the the 2 ready handlers.