Skip to content Skip to sidebar Skip to footer

Why Jquery Event Not Firing When Outside Ready Function, Even After Document Is Ready?

Why does click event not firing in this case, although DOM appears to be loaded ('ready' shows in the console)? $(document).ready(function() { console.log('ready!'); }); $('p'

Solution 1:

$(document).ready is asynchronous. You are passing a callback function to it so that it logs the fact the DOM is ready. However, the click binding code is being executed immediately after you set up the ready handler, not when the callback has executed.

You just need to make sure you put the binding logic within the ready handler.

Solution 2:

If you want that code to be executed in the "ready" event, just move it there.

$(document).ready(function() {
    console.log("ready!");

    $("p").click(function() {
        alert("You clicked on paragraph.");
    });
});

The way you defined it right now doesn't mean it is executed when the DOM is loaded.

Solution 3:

You can place the code directly in the $(document).ready() function or create a new function that binds the click when the DOM is ready.

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

    functionbindClickEvent() {
       $("p").click(function() {
           alert("You clicked on paragraph.");
       });
    }
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script><p>Click me!</p>

Post a Comment for "Why Jquery Event Not Firing When Outside Ready Function, Even After Document Is Ready?"