Reputation: 18792
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
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
Reputation: 141879
One way to do it is :)
$('#checkToggle').click(doToggle).click();
Upvotes: 2
Reputation: 65264
like this...
$(function() {
$('#checkToggle').bind('click.toggle',function(){
$("#toggle-fields").toggle(!this.checked);
}).trigger('click.toggle');
});
Upvotes: 2