i’m slowly getting my head around jQuery and learning more each day, however I wonder if I can create cleaner code. I have heard of ‘chaining’ but am not sure how I apply this.
Below is a piece of working jQuery i’ve written, but although it works, can I reduce it/make it cleaner by chaining any of it?
The script removes a class on button click and adds another class whilst simultaneously hiding another div. At the end I have added on keydown events to use as well as button presses.
<script type="text/javascript">
$('button').click(function(e) {
if ($(this).hasClass('grid')) {
$('#primary ul').removeClass('stylelist').addClass('grid');
$('#primary ul .single-style-text').hide();
}
else if($(this).hasClass('list')) {
$('#primary ul').removeClass('grid').addClass('stylelist');
$('#primary ul .single-style-text').show();
}
});
$(document).bind('keydown', function(e) {
if (e.which == 71) {
$('#primary ul').removeClass('stylelist').addClass('grid');
$('#primary ul .single-style-text').hide();
}
});
$(document).bind('keydown', function(e) {
if (e.which == 76) {
$('#primary ul').removeClass('grid').addClass('stylelist');
$('#primary ul .single-style-text').show();
}
});
</script>
but if its just a list or a grid you want to toggle you can write it on two lines of code. (per event), like: