The basic problem you want to solve is how to relate elements (divs in your case) so that when one is clicked, a related one is shown and the original element is hidden.
There are a number of ways to do this:
- based on the hierarchy (i.e. find the next div)
- arrays of selectors (hard to maintain with the HTML)
- one handler per item (your original, but that does not scale well)
My personal suggestion, in most situations like this, is to "data-drive" the HTML. That is, the HTML is authored to contain enough meta data to allow decisions to be made by relatively simple code. This puts all the maintenance, e.g. for new elements, together with the elements themselves.
One easy way to data-drive is to use data- attributes on the elements e.g. to hold selectors for their related elements.
e.g. this is an explanatory example (so is not the minimum code required):
HTML:
<div class="one" data-target=".one_new">
<h2>Test one</h2>
</div>
<div class="one_new" style="display:none;">
<h2>Test one new</h2>
</div>
<div class="two" data-target=".two_new">
<h2>Test two</h2>
</div>
<div class="two_new" style="display:none;">
<h2>Test two new</h2>
</div>
jQuery
$(document).on('click', 'div', function () {
// Only bother to wrap this once - common practice
var $this = $(this);
// Get the data-target element from the div clicked
var target = $this.data('target');
// If it has a target...
if (target) {
// use it as a jQuery selector to select the matching div
$(target).css('display', 'table');
$this.hide();
}
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/mkLqvrrm/2/
This method uses a single delegated event handler, attached to a non-changing ancestor element. document is the best default if nothing else is closer/convenient. It works by listening for the event (i.e. click) to bubble up to the ancestor. It then applies a jQuery selector to the elements in the bubble chain only. It then applies the function to only the matching elements that caused the event.
This method is very efficient to connect and the runtime overhead, at event time, is negligible (as you can't click the mouse fast enough to notice any difference compared to a directly connected event handler).
<div>?<div class="one clickme">Click Me!</div><div class="two clickme">Click me too!</div>