A little something about everything

internet marketing and website development made simple..

lightweight Javascript toggle function without jquery to display block/none for an element

Here is a quick lightweight javascript toggle function for sites where you dont want to use jquery.

The JavaScript:

<script>
function toggle(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
var list = document.getElementsByClassName("tmc");
for (var i = 0; i < list.length; i++) {
list[i].style.display="none";
e.style.display = 'block';
}
}
</script>

Some example CSS:

<style>
.dbn {
display:block;
float:right;
width:40vw;
border:.05em solid #000;
padding:.8em;
margin:1em;
box-shadow:0 0 .3em #000;
}
#aa {background-color:#f00;}
#bb {background-color:#0f0;}
#cc {background-color:#00f;}
</style>

Some excmple HTML:

<ul>
<li><a onclick="toggle('aa');" style="cursor:pointer ">one</a></li>
<li><a onclick="toggle('bb');" style="cursor:pointer ">two</a></li>
<li><a onclick="toggle('cc');" style="cursor:pointer ">three</a></li>
</ul>
<div id="aa" class="dbn">
Content of Div aa
</div>
<div id="bb" class="dbn">
Content of Div bb
</div>
<div id="cc" class="dbn">
Content of Div cc
</div>

Example:

Content of Div aa
Content of Div bb
Content of Div cc

Add comment

Loading