Search code examples
jquerydocument-readyjquery-on

jquery on function and document ready


I use the jQuery on() function to attach an onclick function to a set of anchors in my website as follows:

<ul>
  <li>First <a href='#' title='delete' class="itemDelete">x</a></li>
  <li>Second <a href='http://www.repubblica.it' title='delete' class="itemDelete">x</a></li>
  <li>Third <a href='#' title='delete' class="itemDelete">x</a></li>
</ul>​

<script type="text/javascript">
$(document).on('click', '.itemDelete', function(e) {
    $(this).closest('li').remove();
    e.preventDefault();
});
</script>

Should I insert the javascript code in the following block?

$(document).ready(function() {
  ...
});

If yes, why?


Solution

  • That piece of code does not require document content to be fully parsed in any case because you are using document which always exists. The selector passed as second argument is not used in any way to retrieve elements, so the dom doesn't need to be ready for this.

    You wouldn't be able to call $(document).ready in the first place if the above wasn't the case.

    It's important to understand that behind the scenes you are attaching a direct, normal event listener to document. All the selector practically does is that your handler callback is not called if no elements matched your selector in the event propagation path. And obviously if propagation is stopped prematurely by lower level listeners, it wouldn't be fired in that case either.