Should I put "Event listeners" inside the "Document ready" function?

Asked

Viewed 179 times

1

I am using an Event Listener to catch the click on an element with jQuery:

$('#elemento').on('click', function () {
    ...
});

My question is whether I should put this "Event Listener" inside the "Document ready" function of the form below or not need?

$(document).ready(function(){
    $('#elemento').on('click', function () {
        ...
    });
});

Can I leave it out as in the first block? What is the best way to do it?

2 answers

1


When you do it the first way, putting inside the $(document).ready(function(){ ... }), you will be instructing the browser to only run its script after the DOM is fully processed.

How an HTML file is interpreted from top to bottom, making the second way and putting the "Istener" out of the $(document).ready(function(){ ... }) you do not guarantee that your script will find the element with ID #elemento. In case for example, you have put your script on <head> of your HTML, it will be executed immediately and will not be able to correctly uncialize your "Event Listener".

An alternative is to put the "Systener" boot out of the $(document).ready(function(){ ... }), but excommunicate your script at the end of HTML, before closing the tag <body>.

  • Moreover jquery mutes errors that would be logged in if you were doing the same thing (linking event to non-existent element) in pure js.

0

Hello, Thiago!

When you do

$(document).ready(function(){
    $('#elemento').on('click', function () {
        ...
    });
});

You ensure that the event is only available when the document is fully loaded. But that’s your decision, if you prefer, you can just do

$('#elemento').on('click', function () {
     alert("Hello!");
});

As it says in the documentation

[O código] será executado uma vez que a página, Document Object Model (DOM), esteja pronta para o código JavaScript executar [seguramente].

jQuery Doc

Browser other questions tagged

You are not signed in. Login or sign up in order to post.