HookedHangman
HookedHangman

Reputation: 35

Why is this causing an uncaught type error

Can anyone help me with why this is throwing an uncaught type error argument 2 is not an object? I know it's in window.addEventListener('load', fadeEffect); I'm busy learning JS so struggling to figure it out.

const preloader = document.querySelector('.preloader');

const fadeEffect = setInterval(() => {

    if (!preloader.style.opacity) {
        preloader.style.opacity = 1;
    }
    if (preloader.style.opacity > 0) {
        preloader.style.opacity -= 0.1;
    } else {
        clearInterval(fadeEffect);
    }
}, 100);

window.addEventListener('load', fadeEffect);

Upvotes: 0

Views: 232

Answers (1)

Derek Wang
Derek Wang

Reputation: 10194

The return value of setInterval is a number representing the ID value of the timer that is set.

And the second parameter on window.addEventListener should be function.

So you need to make fadeEffect as function as follows.

const preloader = document.querySelector('.preloader');

const fadeEffect = () => setInterval(() => {

    if (!preloader.style.opacity) {
        preloader.style.opacity = 1;
    }
    if (preloader.style.opacity > 0) {
        preloader.style.opacity -= 0.1;
    } else {
        clearInterval(fadeEffect);
    }
}, 100);

window.addEventListener('load', fadeEffect);
<div class="preloader">Preloader</div>

Upvotes: 2

Related Questions