Joanna Joanna - 11 months ago 57
Javascript Question

Variables defined in addEventListener JavaScript

I have the code below in the beggining of my JS scirpt. When I try to print any of defined variables below that code, the console says that variables are not defined. Can you tell me why? Maybe I should call the funtion first?
When I define variable below and then print it to the console, it works fine.

Here is the code:

document.addEventListener("DOMContentLoaded", function(){
var homeElement = document.getElementById("home");
var childElements = document.querySelector(".oferts").children;
var banner = document.querySelector(".ban");
var blocks = document.querySelectorAll(".block");
var links = document.querySelector(".links").children;


console.log(homeElement); //Here I got info that this variable is not defined

Thanks in advance for your help!

Abk Abk
Answer Source

Your variables were defined locally and cannot be accessed outside the function.

You can remove the var keyword to make the variables global and you will be able to call the variable anywhere in the script.

Read about JavaScript scope

Javascript local and global variable confusion

Demystifying JavaScript Variable Scope and Hoisting

JavaScript Scope