Sliding Div Function


/ Published in: JavaScript
Save to your folder(s)

This assumes HTML that looks like this:

<pre><code>
&lt;div id=&quot;containing_div&quot;&gt;
&lt;div id=&quot;div_1&quot; style=&quot;background-color:red&quot; class=&quot;visible_div&quot;&gt;
&lt;p&gt;Test Content 1&lt;/p&gt;
&lt;/div&gt; &lt;!-- div_1 --&gt;
&lt;div id=&quot;div_2&quot; style=&quot;background-color:blue&quot;&gt;
&lt;p&gt;Test Content 2&lt;/p&gt;
&lt;/div&gt; &lt;!-- div_2 --&gt;
&lt;div id=&quot;div_3&quot; style=&quot;background-color:yellow&quot;&gt;
&lt;p&gt;Test Content 3&lt;/p&gt;
&lt;/div&gt; &lt;!-- div_3 --&gt;
&lt;/div&gt; &lt;!-- containing div --&gt;
&lt;ul id=&quot;test_buttons&quot;&gt;
&lt;li&gt;&lt;a href=&quot;#&quot; id=&quot;div_1_link&quot; onclick=&quot;slideDiv(&#x27;div_1&#x27;)&quot; class=&quot;here&quot;&gt;One&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#&quot; id=&quot;div_2_link&quot; onclick=&quot;slideDiv(&#x27;div_2&#x27;)&quot;&gt;Two&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#&quot; id=&quot;div_3_link&quot; onclick=&quot;slideDiv(&#x27;div_3&#x27;)&quot;&gt;Three&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt; &lt;!-- test_buttons --&gt;

</code></pre>


And CSS that looks like this:

.hidden_div {
display: none;
}

.visible_div {
display: block;
}

#containing_div {
width: 300px;
background-color: #ddd;
height: 300px;
overflow:hidden;
}
#containing_div div {
width: 300px;
height: 300px;
}

#test_buttons {
background-color: green;
float: left;
padding: 10px 0 10px 0;
}

#test_buttons li {
display:inline;
float: left;
list-style-type:none;
text-align: center;
}
#test_buttons li a {
display: block;
float: left;
width: 50px;
margin-left: 10px;
height: 15px;
background-color: white;
padding: 8px 4px;
}
#test_buttons li a.here {
background-color: orange;
}
#test_buttons li a.not_here{
background-color: white;
}

Change attributes at will, except for display: none or block.


Copy this code and paste it in your HTML
  1. function slideDiv(divId) {
  2. var contDiv = document.getElementById('containing_div');
  3. var divs = contDiv.getElementsByTagName('div');
  4.  
  5. for (var x = 0; x < divs.length; x++){
  6. if (divs[x].id != divId) {
  7. divs[x].className = "hidden_div";
  8. document.getElementById(divs[x].id+'_link').className = 'not_here';
  9. }
  10. else if (divs[x].id = divId) {
  11. divs[x].className = "visible_div";
  12. document.getElementById(divId+'_link').className = 'here';
  13. }
  14. }
  15. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.