Tutorial :jQuery function used as event handler and for initialization


I'm doing this over and over, and I'm not sure if it is the best way to do so in JavaScript/jQuery. I have a function that acts as an event handler, but also I need to call it on page initialization. Thus I have been using the following code:

<script type="text/javascript">      $(function() {          function doToggle() {              $("#toggle-fields").toggle(!$('#checkToggle').is(':checked'));          }          doToggle();            $('#checkToggle').click(doToggle);      });  </script>  

How do you tackle this repetitious situation? Are there any best practices that you can point me toward?


One way to do it is :)



like this...

$(function() {      $('#checkToggle').bind('click.toggle',function(){          $("#toggle-fields").toggle(!this.checked);      }).trigger('click.toggle');  });  


Your code will not work because this will be window in the first call.

Change it to


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »