1

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?

6
  • what exactly is your question? Commented Jul 27, 2010 at 4:47
  • I don't see any repetition there. Commented Jul 27, 2010 at 4:48
  • Sorry, was a little too fast with my cut-and-paste, the code I originally put up would not actually work. Concept is still the same though. Commented Jul 27, 2010 at 4:54
  • @DavGarcia - so was I, with your code :) Commented Jul 27, 2010 at 4:56
  • @DavGarcia - does your initialization and handler code always/only manipulate DOM elements as in above example? Commented Jul 27, 2010 at 5:31

3 Answers 3

2

One way to do it is :)

$('#checkToggle').click(doToggle).click();
Sign up to request clarification or add additional context in comments.

4 Comments

Note that this will also trigger other handlers.
@SLaks - that's true, but I'm thinking of this from a UI perspective. Put the application in an initial state that it would be in if the element was clicked (which means all attached handlers will indeed run).
Good idea. However, if he has non-idempotent handlers, he should be aware of that.
@Reigel - Namespacing is definitely not a bad idea at all. In fact, it is a very good idea.
2

like this...

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

Comments

2

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

Change it to

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.