0

I have the following piece of code in my javascript file(helper.js):

var a = $('li')
$(window).keydown(function(e) {
    \\whatever
})

it is supposed to select all

  • tags in my html file and store in in a, however when I use this code, it a is null(which it shouldn't be). when I change my code to:
    
    $(window).keydown(function(e) {
        var a = $('li')
        \\whatever
    })
    

    a is initialized correctly. Does anyone knows why? I am using jquery 3.3.1.

  • Tim Lu
    • 9
    • 1
      I'm guessing it's because your scripts are included in some place (like the in the tag) where they're loaded *before* the actual HTML DOM is rendered. Which means when that JS is loaded and run, the DOM is empty, and after the JS scripts are loaded your DOM is rendered and populated. But since in the 1st example it's a global variable, it's only calculated once when the script loads. The second one works because the fetching of all those `li` elements happens not when the page loads, but when the function is called (i.e. when a key is pressed). By which time the DOM is populated – Jayce444 Jan 03 '21 at 06:14
    • Wrap it all into a document ready function and it will work. – ptts Jan 03 '21 at 09:04

    1 Answers1

    -1

    If you are dealing with the DOM (Document Object Model), use $(document).

    If you are dealing with how user interact with the window, screen and so on, use $(window)

    Here is a link for better understanding window and document

    Window vs Dom

    Kopi Bryant
    • 1,139
    • 12
    • 26