Monday, October 26, 2009

How to create a simple accordion using Javascript and Css?

this code will show you how to create a simple accordion using javascript and css. 
here is the html code.....








<html>
<head>
<title;gt;Accordion sample</title>
<link rel="stylesheet" type="text/css" href="toggle.css" /> 
<script type="text/javascript" src="toggle.js" >
</script>
</head>
<body>
<h1>Accordion Sample</h1>
<div class="accordion_tab" onclick="showTab('accordion_1_body', 'accordion_2_body');">
<span gt;Accordion Tab 1</span>
</div>  
<div id="accordion_1_body" class="hide_tab">
<span style="color: white">You can put your content here</span>
</div>
<div class="accordion_tab" onclick="showTab('accordion_2_body', 'accordion_1_body');">
<span>Accordion Tab 2</span>
</div>
<div id="accordion_2_body" class="hide_tab">
<span style="color: white">You can put your content here</span>
</div>
</body>
</html>


here is the css code. you can name this file anything you want. for me, i named it toggle.css






.accordion_tab {
background-color: #780000; 
border: 1px solid #E00000;
cursor: pointer;
}
.accordion_tab span {
color: white;
font-weight: bold;
padding: 5px 10px;
}


.hide_tab {
background: black;
display:none;
}
.show_tab {
background-color: #F00000;
height: 150px;
}


here is the javascript code.....
i named it toggle.js....








function showTab(show_id, hide_id){
        
var show = document.getElementById(show_id);
if(show.className == "show_tab"){
document.getElementById(show_id).className = "hide_tab";
} else {
document.getElementById(show_id).className = "show_tab";
}


}




In that code everytime the html div tab is clicked it calls the javascript showTab() function which as you can see checks for the name of the class of the certain div. if the class is named show_tab then it alters the class name into hide_tab and vice versa.  As you can see, its really that simple to create an accordion using javascript and css.

No comments:

Post a Comment

Feeds

Sonic Run: Internet Search Engine javascript, coldfusion, programming, simple programming teckniques, css, html Webfeed (RSS/ATOM/RDF) submitted to http://www.feeds4all.nl Web Development & Design Blogs DigNow.net

Search Engine Optimization and SEO Tools
javascript, coldfusion, programming, simple programming teckniques, css, html