At first, I thought this was going to be a nightmare but thankfully I was wrong! That said, it's not easy peasy so I'll show you the amended code first and explain what's going on later.
PHP Code:
$(document).ready(function() {
// By default, reveal the first menu item automatically.
// If JavaScript is loaded with menu.js?show=something
// And the "something" item exists in the menu, then that
// item will be revealed instead.
var szDiv = 'div.menu > h3:not(:first) + div';
var aShow = $('head > script[src^="menu.js"]:first').attr('src').match(/show=([^&]*)/);
if (aShow && aShow[1] != "" && $('div.menu > h3:contains("' + aShow[1] + '")').length > 0) {
szDiv = 'div.menu > h3:not(:contains("' + aShow[1] + '")) + div';
}
$(szDiv).hide();
$('div.menu > h3').click(function() {
$(this).next('div').slideToggle('fast', function() {
$(this).siblings('div:visible').slideUp('fast')
});
});
});
Because you're going to be telling the script what to open by changing the HTML, it makes sense to have some kind of default action if/when you don't want to provide an item to show (via
?show=something) or if that item does not exist in your menu. The line starting
var szDiv... stores a default selector to use in these cases. I'm not sure if you'll understand the selector syntax but basically by default we'll be telling everything but the first menu item to hide itself.
The next line, starting
var aShow... is pretty complicated but shows the power of frameworks like jQuery. I'll go through step by step.
$('head > script[src^="menu.js"]:first') is another complicated selector but don't let that put you off. All we're doing here is grabbing the first (if any) element in the HTML document which is a SCRIPT element within the HEAD of your HTML and has the SRC attribute pointing to our
menu.js file. The next part,
attr('src'), simply grabs the SRC attribute from that SCRIPT element. With
match(/show=([^&]*)/) we text that SRC attribute against a
regular expression which pulls out the provided
show, if there is one.
The next line (the
if statement) just checks to see whether we could actually pull out the item to show or not. If we could grab an item to show, then we change
szDiv to a new selector which makes jQuery display that item rather than the default.
$(szDiv).hide(); then puts all of the above into action by hiding items which match the
szDiv selector. This results in all of the divs being hidden except our chosen one, or the first one (default) if no item is chosen.
The rest of the script is identical to before, simply assigning something to do when the headings are clicked.