Tutorial :jQuery function used as event handler and for initialization



Question:

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?


Solution:1

One way to do it is :)

$('#checkToggle').click(doToggle).click();  


Solution:2

like this...

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


Solution:3

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

Change it to

doToggle.call(document.getElementByID('checkToggle'));   

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