The question I would like to ask is if the Javascript snippet below is well formatted and structered in terms of Javascript/jQuery syntax, readability and speed.
The function of this piece of code is to provide a tabbed interface where through clicking the tabs different parts of content are shown. I could of course use a plugin, however I’d like to keep it simple. It works fine the way I wrote it now, but I would like to know if there are improvements to be made in order to learn a correct style and manner of coding.
// Wrap in anonymous function to not pollute the global namespace
(function() {
// Hide all wrappers.
// If javascript is disabled then all wrappers have to be visible.
$('#main .wrapper').hide();
// Show selected wrapper. This class is set in the HTML that is loaded.
// The wrapper has the id of the html, perhaps using href is better?
var html = $('.nav a.selected').html().toLowerCase();
$('#main #' + html).show();
// Show selected wrapper on click event
$('.nav a').click(function(){
// Remove selected class all tabs
$('.nav a').removeClass('selected');
// Hide all wrappers and remove selected class from all wrappers
$('#main .wrapper').hide();
// Add selected class to new tab
$(this).addClass('selected');
//Show selected wrapper
var html = $(this).html().toLowerCase();
$('#main #' + html).show();
return false;
});
}());
I hope you can give me some advise and suggestions for correct and elegant coding. Thanks in advance!
None of the selectors are optimized for speed or cached. As jQuery goes, I’ve seen worse and it will probably work fine. As high-performance, professional JavaScript goes, it gets a D-.
If you want to work on your performance, get very familiar with the work of Nick Zackas and other performance gurus who do presentations and write books on the subject. Rely as little as possible on jQuery. Use JSPerf religiously. Question everything you write and leave comments when you’re unsure or think it can be done better in future implementations.
Good luck to you, the results are worth the journey.