DavGarcia
DavGarcia

Reputation: 18792

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?

Upvotes: 1

Views: 661

Answers (3)

SLaks
SLaks

Reputation: 887453

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

Change it to

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

Upvotes: 2

Anurag
Anurag

Reputation: 141879

One way to do it is :)

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

Upvotes: 2

Reigel Gallarde
Reigel Gallarde

Reputation: 65264

like this...

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

Upvotes: 2

Related Questions