Link to home
Start Free TrialLog in
Avatar of dlearman1
dlearman1Flag for United States of America

asked on

Why does JS work in codepen but fails when replicated?

I'm back to working on my window scroll problem. I have created a codepen "https://codepen.io/LuckyDougie/pen/wvpdoMb" that does function as expected - background-color and text color change when window is scrolled.

My problem is the JS does not work when used within the site code. Basically, nothing happens. It behaves like the "window.addEventListener("scroll", () => { " function is never executed.  The console.log is completely blank.

I'm new to codepen, is codepen adding some functionality in the background to help run this script; or does anyone have an idea of why the script is good in codepen and fails when replicated in the actual code?

Thanks


Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Hey there,

My guess is that your script is loading before your DOM (HTML elements). You need to either defer your script (by running it in the DomReady event, or by moving your script tags to the end of your document - i.e. just before the closing </body> tag.
I suggest you

1. move the call to navUpdate to after the definition
2. make it a const, because without var, let or const, it is polluting the window object
3. wrap all in DOMContentLoaded event

https://codepen.io/mplungjan/pen/RwxVLKe

window.addEventListener("DOMContentLoaded", function () {
    const navBacker = document.querySelector(".l-nav");
    const navLinks = document.querySelectorAll(".c-menu__item > a");

    console.log({ navBacker });
    console.log({ navLinks });

    const navUpdate = () => {
        console.log("*** navUpdate was called ***");
        if (document.documentElement.scrollTop > 50) {
            navBacker.classList.add("js-nav-backer");
            console.log(navBacker.classList.contains("js-nav-backer"));

            // Change the color of links on scroll
            for (let i = 0; i < navLinks.length; i++) {
                const element = navLinks[i];
                element.classList.add("text-black");
                console.log(element.classList.contains("text-black"));
            }
        } else {
            //console.log("scrollTopnot > 50 called");
            navBacker.classList.remove("js-nav-backer");

            // Change the color of links back to default
            for (let i = 0; i < navLinks.length; i++) {
                const element = navLinks[i];
                element.classList.remove("text-black");
            }
        }
    };
    window.addEventListener("scroll", () => {
        console.log("*** scroll event listener ***");
        navUpdate();
    });
});

Open in new window

Avatar of dlearman1

ASKER

Chris. The script is loading just before </body> tag. My code is plain JS. Is there a JS equivalent to jQuery’s $.ready()?
Yeah - the vanilla version is the DOMContentLoaded event:

window.addEventListener('DOMContentLoaded', () => {
  // wrap you code in here.
});

Open in new window

Michel... I made the code additions you suggested. Still no change in behavior. The console.log does show the first two comments:
Object { navBacker: nav.l-nav } main.js:97:11
Object { navLinks: NodeList(6) }
but nothing after that.
Do you have a live link we can take a look at. And what browser are you running ??
Chris... This was also suggested by Michel and I did make the changes. Still no real output, but The console.log does show the first two comments (they were also showing before the changes):
Object { navBacker: nav.l-nav } main.js:97:11
Object { navLinks: NodeList(6) }
but nothing after that.
Very weird
If I test the code that you've posted, it works exactly as it should, so fundamentally, there's nothing wrong with it. The reason I ask for a live link is so that we can see what else is interfering with the code - there must be more going on in your code than you've shown on the CodePen, but unless we can see your code, we're left guessing. As it stands, the code here works fine.
I have posted to a live site at http://www.serenaconstruction.com/beta/index.htm. Thanks for your help. I'm using FF Developer ver: 96.0b10 and local testing server running under MAMP.
ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hey Chris,
Deleting the overflow-y from HTML did the trick. Thank you. I would have been head scratching for a long time on this one. I also deleted this from the body tag. Honestly, I'm not sure why I put them there in the first place. Maybe I'll find out eventually, but for now we've moved the ball down the court.
Happy Days :)