-2

this is a function that suppose to show the Date in the website when i move the mouse around it, i am learning right now es6 and got excited to use the new way of using functions but for some reason it dosnt work and i would be glad if some one helped me to understand why it doesnt work /=. oh and if it will help i also copied the error "Uncaught ReferenceError: Cannot access 'Time' before initialization" no idea how to deal with it.

//Time script
const question = document.querySelector(`.timeleftstyle`)

question.addEventListener(`mouseover`,Time);
question.addEventListener(`mouseout`,hide);


const Time = () => {
    const clock = document.querySelector(`.thetime`);
    clock.innerHTML=Date();
    
}

const hide = () => {
    const clock = document.querySelector(`.thetime`);
    clock.innerHTML=``;
}
Kayoku
  • 17
  • 5

2 Answers2

2

You have to move your functions above the using, in your code:

//Time script

    const question = document.querySelector(`.timeleftstyle`)
    
    const Time = () => {
        const clock = document.querySelector(`.thetime`);
        clock.innerHTML=Date();
        
    }
    
    const hide = () => {
        const clock = document.querySelector(`.thetime`);
        clock.innerHTML=``;
    }
    
    question.addEventListener(`mouseover`,Time);
    question.addEventListener(`mouseout`,hide);
ESI
  • 1,657
  • 8
  • 18
1

The problem relates to hoisting. Both Time and hide are set after your event listeners. And while the browser "hoists" both to the top of your code, they remain uninitialized. They remain, without a defined value at the time your addEventListener uses them. The solution is as Ester has already stated. To move your addEventListener after Time and hide are declared.

Saahir Foux
  • 654
  • 4
  • 12
  • 27