I have following code that works –
$(function(){
$('#testbutton').click(function(){
var checkedValue = $('[name="someRadioGroup"]:radio:checked').val();
$('#result').html('The radio element with value <tt>' + checkedValue + '</tt> is checked');
});
});
I understand that $(‘#testbutton’) fetches the HTML element with id testbutton and assigns an event handler to it.
But I don’t understand why I need to put that code inside a function literal?
If I remove the $(function(){ (and the corresponding }); ) it does not work.
However other code can work without being wrapped in a function literal. Example –
alert('Hi there')
What is the difference? Why does alert work but the event assignment statement does not?
It is not a requirement.
You are putting your code in an event handler that is invoked when the DOM is ready.
If you don’t put your code in a DOM ready handler, and if your code performs DOM selection, you need to find some other way to to make sure the DOM is ready before it runs.
If your code doesn’t perform DOM selection, then it’s not needed. That’s why your
alert()works, because it doesn’t need to fetch any elements.An alternative is this.
This places your code below all the elements on the page, so they are certain to be available when your code runs.
Another alternative is to use a
window.onloadhandler.or using jQuery.
This is similar to the DOM ready handler, except that it waits for all resource, like images, to be loaded.