kuba
kuba

Reputation: 1009

Difference between on() and direct event binding

I have a webpage with jQuery (it seems that version does not matter) on Chrome. The page is fully loaded. I'm writing this in the Chrome console:

$(document).on('ready', () => {console.log('Hello');});

I get no 'Hello' in the console. However when writing this:

$(document).ready(() => {console.log('Hello');});

'Hello' is in the console now.

There is nothing special about that in the documentation, so why it is working in such a way? I've always thought that the on() function is just a syntax sugar.

Upvotes: 2

Views: 73

Answers (1)

Shinjo
Shinjo

Reputation: 695

http://api.jquery.com/ready/

There is also $(document).on( "ready", handler ), deprecated as of jQuery 1.8 and removed in jQuery 3.0. Note that if the DOM becomes ready before this event is attached, the handler will not be executed.

I fail to understand what you mean by "Nothing special about that in documentation, so why it is working in such a way? I've always thought that on() function is just a syntax sugar"

Since it was stated quite clearly. Unless you're using jQuery < 3.0.

Alternatively, you could use:

$(function(){
   console.log('Hello');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 2

Related Questions