Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need to wrap my JQuery code in a function literal?

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?

like image 427
Kshitiz Sharma Avatar asked Oct 14 '25 08:10

Kshitiz Sharma


1 Answers

$(function(){...}); is shorthand for $(document).ready(function(){...});. The purpose of it is to not run your code until the elements that you intend to work with exist in the DOM (which generally is after the document is ready.)

like image 58
Kevin B Avatar answered Oct 16 '25 22:10

Kevin B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!