How can I write this jQuery more efficiently? The goal is to be able to click on a menu item in one div (left column), and change the contents in another div (right column). Here’s what I have so far:
$(document).ready(function(){
$('#content1').hide();
$('#content2').hide();
$('#content3').hide();
$('#content4').hide();
$('#link1').click(function(){
$('#content1').show('slow');
$('#content2').hide();
$('#content3').hide();
$('#content4').hide();
});
$('#link2').click(function(){
$('#content1').hide();
$('#content2').show('slow');
$('#content3').hide();
$('#content4').hide();
});
$('#link3').click(function(){
$('#content1').hide();
$('#content2').hide();
$('#content3').show('slow');
$('#content4').hide();
});
$('#link4').click(function(){
$('#content1').hide();
$('#content2').hide();
$('#content3').hide();
$('#content4').show('slow');
});
});
UPDATE:
This is the latest jQuery code I have that I can’t get to work. When I navigate to my page, all the content currently appears, but should be hidden. When I click on the links, nothing happens. All sections remain showing
$(document).ready(function() {
var contents = $('.content')
$('#nav a').click(function(e){
e.preventDefault()
var target = $(this.href)
target.show()
contents.not(target).hide()
});
});
Here we go:
But, this is error prone and not very mantainable, if not convoluted. This is why we have classes. Give a common class to your “content” elements, and you probably already have a meaningful structure for the links (which in turn should point to their respective target’s IDs):
So you can turn this into something more straight-forward: