Reputation: 299
How to write my own toggle function in jquery.
<head> <script type="text/javascript" src="jquery-1.3.2.min.js"></script> <script> $(function(){ $('#dv').bind('click',function(){ $("#toTgl:hidden").show(); }); $('#dv').trigger('click'); }); </script> </head> <body> <div id='dv' onclick="$('#toTgl').hide()"><center>Toggle</center></div> <br/> <div id='toTgl'><center>Change This</center></div> </body>
Both (show & hide) gets triggered and I
Upvotes: 1
Views: 1939
Reputation: 299
Here's what I came with and was working fine.
<div id='dv' onclick="alert('test')">Toggle</div>
<br/>
<div id='toTgl'>Change This</div>
<script>
function toggle(){
$('#toTgl')[$('#toTgl').is(':hidden')?'show':'hide']();
}
function toggleClick(ele){
$(ele).removeAttr('onclick');
$(ele).bind('click', function(ev){
toggle();
});
}
function z(id){ return document.getElementById(id);}
toggleClick(z('dv'));
</script>
Upvotes: 2
Reputation: 700152
You have added two click events that conflict. Use a single event handler that shows and hides the element. (And don't use the deprecated center
tag.)
<head>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(function(){
$('#dv').click(function(){
$("#toTgl").toggle();
});
});
</script>
<style type="text/css">
#dv { text-align: center; }
#toTgl { text-align: center; }
</style>
</head>
<body>
<div id="dv">Toggle</div>
<br/>
<div id="toTgl">Change This</div>
</body>
Upvotes: 0