What is the correct way to make the following code reusable (so that I don’t have to have so many versions of the same function each time that I want to hide/show a set of DIVs):
// instructions
$('#hideInstructionsOverview').click(function() {
$('#instructionsOverview').fadeOut(400, function () {
$('#instructionsDetail').fadeIn(400);
});
});
$('#hideInstructionsDetail').click(function() {
$('#instructionsDetail').fadeOut(400, function () {
$('#instructionsOverview').fadeIn(400);
});
});
// group
$('#hideGroupOverview').click(function() {
$('#groupOverview').fadeOut(400, function () {
$('#groupDetail').fadeIn(400);
});
});
$('#hideGroupDetail').click(function() {
$('#groupDetail').fadeOut(400, function () {
$('#groupOverview').fadeIn(400);
});
});
The above code is used in the same way to hide “instructions” and “group” divs (and about 7 other divs in the same manner). The similar way that each is called is with this code:
<a id="hideInstructionsOverview" href="javascript:void(0);"><img src="img/misc/plus.png" alt="" width="40" height="40" border="0"></a>
<a id="hideInstructionsDetail" href="javascript:void(0);"><img src="img/misc/minus.png" alt="" width="40" height="40" border="0"></a>
<a id="hideGroupOverview" href="javascript:void(0);"><img src="img/misc/plus.png" alt="" width="40" height="40" border="0"></a>
<a id="hideGroupDetail" href="javascript:void(0);"><img src="img/misc/minus.png" alt="" width="40" height="40" border="0"></a>
I’m thinking that there’s a way that I can create a function that accepts variables, and that I pass three variables on click: (1) what image id was clicked (I think that $this is probably used), (2) what div to fadeOut and (3) what div to fadeIn. I can’t seem to get the variable creation and passing correct, but I imagine that the final, reusable function would look something like this:
// divToggler
$('$this').click(function() {
$('#divToFadeOut').fadeOut(400, function () {
$('#divToFadeIn').fadeIn(400);
});
});
Thanks so much in advance!
Berklie
Ideally you would tackle this hierarchically rather than relying on lots of IDs. This is not always possible, and since you didn’t post your HTML structure, I’ll just answer the question at hand. Note, this utilises ECMA 5’s
Object.keys()method. It would need modifying for use in IE <= 8.It could be made shorter still with some assumptions about naming conventions (which appear sound, from what you posted) but I won’t risk that one.