1
votes

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

3

3 Answers

2
votes

Why don't you use the build-in jQuery toggle function?

1
votes

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>
0
votes

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>