Ryan Bennett Ryan Bennett - 2 months ago 18
Javascript Question

How to toggle between two divs

I am trying to toggle between two divs. For example, onload, I want the left content to show and the right content will remain hidden. If I click the right div, I want the left content to hide and the right content to appear and vise versa. I am very new to javascript but here is what I have. I can't seem to get it to work. Please help...

Here is my HTML code:

<div onclick="toggle_visibility('left');">

<div onclick="toggle_visibility('right');">

<div id="left" style="display: block;">
This is the content for the left side

<div id="right" style="display: none;">
This is the content for the ride side

Here is the Javascript I am using:

<script type="text/javascript">
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
e.style.display = 'block';


Live demo: http://jsfiddle.net/PauWy/1/


<p id="toggle">
    <span> Left </span>
    <span> Right </span>

<div id="left"> LEFT CONTENT </div>
<div id="right"> RIGHT CONTENT </div>


$('#toggle > span').click(function() {
    var ix = $(this).index();

    $('#left').toggle( ix === 0 );
    $('#right').toggle( ix === 1 );

CSS (to hide the right DIV onload):

#right { display:none; } 

Put the JavaScript code at the bottom of the page.

        $(function() {        
            // put jQuery code here    

Notice how the SCRIPT element is located at the end of the BODY element. Also, notice that the jQuery code should be inside the ready handler: $(function() { ... code ... });