Pure Javascript code to toggle a div
Posted: Sun Feb 17, 2013 10:07 am
Hi there,
I want to toggle a div element onclick a button. But I am unable to do it although I have code to slideup or slidedown a div element seperately. Here is my code for slidedown a div:
and here is my code to slideup a div content
But I want to combine these two functions into one so that it can toggle the div on each click.
I am very weak in javascript and don't want to use jquery only for this function. Any help????
I want to toggle a div element onclick a button. But I am unable to do it although I have code to slideup or slidedown a div element seperately. Here is my code for slidedown a div:
Code: Select all
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<STYLE TYPE="text/css">
#content{
width: 320px;
height: 0.1em;
background-color: #FF3333;
overflow:hidden;
display: block;
visibility: hidden;
}
</STYLE>
<script type="text/javascript">
var inter;var hh=0;
function toggleContent() {
var obj = document.getElementById("content");
if(hh==80)
{
clearInterval(inter);
return;
}
obj.style.visibility = 'visible';
hh+=2;
obj.style.height = hh + 'px';
}
</script>
</head>
<body>
<div ID="content">This is content.</div>
<button onclick="inter=setInterval('toggleContent()',3);">Toggle</button>
</body>
</html>
and here is my code to slideup a div content
Code: Select all
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<STYLE TYPE="text/css">
#content{
width: 320px;
height: 100px;
background-color: #FF3333;
overflow:hidden;
display: block;
visibility: show;
}
</STYLE>
<script type="text/javascript">
var inter;var hh=100;
function toggleContent() {
var obj = document.getElementById("content");
if(hh==2)
{
obj.style.visibility = 'hidden';
obj.style.height = '0.1em';
clearInterval(inter);
return;
}
hh-=2;
obj.style.height = hh + 'px';
}
</script>
</head>
<body>
<div ID="content">This is content.</div>
<button onclick="inter=setInterval('toggleContent()',3);">Toggle</button>
</body>
</html>
But I want to combine these two functions into one so that it can toggle the div on each click.
I am very weak in javascript and don't want to use jquery only for this function. Any help????