Code for keypress function


#1

$(document).keypress(function() {
$('.dropdown-menu').toggle();
});

-

$(document).ready(function() {
$(document).keypress(function() {
$('.dropdown-menu).toggle();
});
});

Hey!

Above are two bits of code which the first was from the Make an Interactive Website course and the second from the jQuery course. Is the difference between the two that the keypress function for the first code would work even if the page hasn't fully loaded? Could someone clarify the differences for me.

Thanks


#2

Yes, there are some differences. In some circumstances you could have a problem if you would use this code:

    $(document).keypress(function() {
     $('.dropdown-menu').toggle();
    });

without $(document).ready(); method.
Let's say that your JavaScript code is defined between head tags, your JavaScript code will be executed first, and jQuery will try to select element/elements that have a class dropdown-menu at this point document object is not loaded fully and jQuery will fail to select that element because it simply doesn't exist. If you put your code before closing body tag and after all defined elements in body tag it shouldn't cause a problem, because HTML tags would be rendered first and after that jQuery code will be executed, so jQuery will find that element successfully.

If you'd put your JavaScript code between head tags and your JavaScript code has some work to do with HTML elements you should always use $(document).ready(); method to ensure that your JavaScript code will be executed only if document object is fully loaded.