I've created a working list switcher here: http://codepen.io/tincanben/pen/GpjbMQ
It's a bit messy so I'd like to know how I can rewrite the code:
$('.switcher a').on('click',function(e) {
if ($(this).hasClass('grid-view')) {
$('#block-listings ul').removeClass('list').addClass('grid');
$('.switcher a.grid-view').addClass('active-grid');
$('.switcher a.list-view').removeClass('active-list');
}
else if($(this).hasClass('list-view')) {
$('#block-listings ul').removeClass('grid').addClass('list');
$('.switcher a.list-view').addClass('active-list');
$('.switcher a.grid-view').removeClass('active-grid');
}
});
So that it's clean and in the format of:
var
// General purpose vars
htmlBody = $('html,body'),
Window = $(window),
Document = $(document),
Switcher = $('#switcher'),
// Switcher
switcher = function(){
var switcher =
},
Ready = function(){
externalLinks();
switcher();
},
May I recommend you put everything in a self invoking function to protect the code from your global scope, I also prefixed jquery objects with the $ sign, its a good practice (like that you know if the object is already wrapped in jquery or not) and then I took your function and removed the double code with the toggleClass function and a slight different approach on how to check against the active-grid class, happy coding.