Here's one way to do it with plain javascript that uses common code for each button, no javascript in your HTML and data attributes:
HTML:
<div id="buttonContainer">
<button data-content="content1">Content 1</button>
<button data-content="content2">Content 2</button>
<button data-content="content3">Content 3</button>
</div>
<div id="contentContainer">
<div id="content1">Showing Content 1</div>
<div id="content2">Showing Content 2</div>
<div id="content3">Showing Content 3</div>
</div>
Javascript:
var buttons = document.querySelectorAll("#buttonContainer button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function() {
var contentItem = this.getAttribute("data-content");
var contents = document.querySelectorAll("#contentContainer div");
for (var j = 0; j < contents.length; j++) {
contents[j].style.display = "none";
}
document.getElementById(contentItem).style.display = "block";
});
}
Working demo: http://jsfiddle.net/jfriend00/rcDXX/
Explanation:
- Create a div that contains the buttons.
- Create a div that contains the various content areas.
- Create CSS rules that show/hide the content for the appropriate starting state.
- Put a data attribute on each button that tells you which content area it should show so you can use generic code for all the buttons.
- Get all the buttons into a nodeList.
- Set a click event handler on each button.
- In that click handler, get the content id that should be shown for that button.
- Hide all the content areas by setting their style to
style.display = "none"
- Show the desired content area.
FYI, here's a little more advanced version of the code that uses a helper function: http://jsfiddle.net/jfriend00/aqMLt/