2

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.

4
  • jQuery's on() function does not introduce any new functionality that did not already exist, it is just an attempt to standardize event handling in jQuery
    – Ghasem
    Commented Apr 15, 2019 at 7:47
  • This was also my intuition - but why there is such a difference?
    – kuba
    Commented Apr 15, 2019 at 7:48
  • 3
    ready is not an event - it's $(document).ready(). It's like asking why you can't do $(document).on("fadeIn"...
    – fdomn-m
    Commented Apr 15, 2019 at 7:49
  • 1
    @freedomn-m is correct. However to answer your general point, ie. What's the difference between click() and on('click'), there isn't one. All shortcut methods call on() internally. Commented Apr 15, 2019 at 7:50

1 Answer 1

2

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>

3
  • 1
    I'm not using new jQuery - and don't need to use, I have asked it just out of curiosity :) by that quote I mean, that there is nothing in documentation about difference between binding with on() and directly using function
    – kuba
    Commented Apr 15, 2019 at 7:55
  • 2
    There isn't a difference between directly binding and using on for events - but document ready is not an event you can bind to. As confirmed in this answer. If you asked the question with an actual event, the answer would be different, but you've asked why $(document).on("ready"... doesn't work - and it doesn't work because it's not an event.
    – fdomn-m
    Commented Apr 15, 2019 at 7:58
  • 1
    Also, it deprecated in 1.8 which was released in 2012 and then removed in 3.0 which was released June 2016 - so hardly "new jquery". Perhaps you could let us know which outdated version of jquery you are using?
    – fdomn-m
    Commented Apr 15, 2019 at 8:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.