0

window.addEventListener for scroll event is not working in my JS. I've tried several ways but still not working. I've used intersectionObserver in the JS also. Here is the JS code

const moveToAbout = () => {
    document.getElementById('about').scrollIntoView(true)
}

const moveToWork = () => {
    document.getElementById('work').scrollIntoView()
}

const moveToTop = () => {
    document.getElementById('main-section').scrollIntoView(true)
}


const options = {
    root: null,
    threshold: 0,
    rootMargin: "-150px"
}

const header = document.querySelector("header")
const sections = document.querySelectorAll(".section")
const mainSection = document.querySelector(".main-container")

const bttWrapper = document.getElementById('bttBtn-wrapper')
const veganImage = document.getElementById('vegan-store-image')
const navbar = document.getElementById('header')



veganImage.onclick = () => {
    window.open("https://thoughtlessmind.github.io/Vegan-store")
}


const sectionOne = document.querySelector(".about-section");
// bttWrapper.style.display = 'none'

const mainObserver = new IntersectionObserver(function (entries, observer) {
    entries.forEach(entry => {

        if (entry.isIntersecting) {
            header.classList.remove("nav-theme-2")
            bttWrapper.classList.add("btnWrapperHidden")
            bttWrapper.classList.remove("btnWrapperShow")
        } else {
            header.classList.add("nav-theme-2")
            bttWrapper.classList.add("btnWrapperShow")
        }


        // console.log(entry.target, '-', entry.isIntersecting)
    });
}, options);


mainObserver.observe(mainSection)


window.addEventListener("scroll", (event)=>{
    console.log("scrolled")
    var scroll = this.scrollY
    if(scroll > 20){
        console.log('reached')
    }
})

const test = () =>{
    console.log('working')
}

window.addEventListener("scroll", test)

window.addEventListener("scroll", () => console.log(window.pageYOffset));


Later in the lower part, I've tried to add scroll event in some ways but nothing is happening. Here is the link for the whole repo: Github repo link

1
  • I've also tried using document instead of window. Commented Apr 26, 2020 at 15:38

2 Answers 2

1

remove height property from CSS main. It is working now :

use min-height, max-height

const moveToAbout = () => {
document.getElementById('about').scrollIntoView(true)
}

const moveToWork = () => {
document.getElementById('work').scrollIntoView()
}

const moveToTop = () => {
document.getElementById('main-section').scrollIntoView(true)
}


const options = {
root: null,
threshold: 0,
rootMargin: "-150px"
}

const header = document.querySelector("header")
const sections = document.querySelectorAll(".section")
const mainSection = document.querySelector(".main-container")

const bttWrapper = document.getElementById('bttBtn-wrapper')
const veganImage = document.getElementById('vegan-store-image')
const navbar = document.getElementById('header')



veganImage.onclick = () => {
window.open("https://thoughtlessmind.github.io/Vegan-store")
}


const sectionOne = document.querySelector(".about-section");
// bttWrapper.style.display = 'none'

const mainObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(entry => {

    if (entry.isIntersecting) {
        header.classList.remove("nav-theme-2")
        bttWrapper.classList.add("btnWrapperHidden")
        bttWrapper.classList.remove("btnWrapperShow")
    } else {
        header.classList.add("nav-theme-2")
        bttWrapper.classList.add("btnWrapperShow")
    }


    // console.log(entry.target, '-', entry.isIntersecting)
});
}, options);


mainObserver.observe(mainSection)

window.onload = () =>{
console.log("loaded");
window.onscroll = function()
{
  console.log("scrolling.....", window.scrollY);
}
}
@import 'global.css';


/* -----Navigation bar styles */
@import 'navbar.css';



/* ----------- Main contaier styles*/
main{
    overflow: scroll; 
    scroll-snap-type: y mandatory;
}

.section{
    /* scroll-snap-align: start; */
    /* Uncomment above to add snap scrolling effect */
    margin-left: auto;
    margin-right: auto;
    width: 80%;
    max-width: 1100px;
    border-bottom: 1px solid grey;
}

.main-container {
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    justify-content: space-between;
}

.name-text{
    font-size: 2.8rem;
    font-weight: 500;
    color: var(--primary-text-color);
}

.intro-text{
    padding: 1rem;
    padding-left: 0;
    font-size: 1.2rem;
    color: var(--para-text-color);
}

.right-container{
    text-align: left;
}

.text-container{
    align-self: center;
}

.left-image{
    width: 200px;
    height: 200px;
    background-color: palegreen;
    animation: rotate 8s infinite ease-in-out ;
}

@keyframes rotate{
    0%{
        border-radius: 0;
    }
    50%{
        border-radius: 50%;
        transform: rotate(145deg);
        background-color: green;
    }
    100%{
        transform: rotate(360deg);
        border-radius: 0;
    }
}



.social-link-container{
    margin-top: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.social-logo{
    font-size: 2rem;
    color: var(--primary-text-color);
}

.social-link{
    margin: 0 10px;
}


/* About section */

.about-section{
    height: 100vh;
    padding-top: 38.5px;
    border-bottom: 1px solid grey;
}

.about-section >  h2{
    padding: 10px 10px 10px 0px;
}


/* ----Work section ---- */

#work{
    height: 100vh;
    padding-top: 38.5px;
}

#work >h2 {
    padding: 10px 10px 10px 0;
}

/* .inverse{
    background-color: #111;
    color: #eee;
} */


.project-card{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    border-radius: 5px;
    margin-top: 15px;
    transition: 0.3s;
}

.project-card:hover{
    background-color: rgba(200, 200, 200, 0.2);
}

.left-side-card{
    padding-right: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    max-height: 145px;
    height: 145px;
}



.project-name{
    margin-bottom: 10px;
    display: inline-block;
}

.project-link{
    text-decoration: none;
    letter-spacing: 0.8px;
    position: relative;
}

.project-name::after{
    position: absolute;
    bottom: 0;
    left: 0;
    content: '';
    height: 1px;
    width: 100%;
    background-color: black;
    /* transform: scale(1); */
    transition: 0.3s;
    transform-origin: left;
}

.project-name:hover::after{
    transform: scale(0);
    transform-origin: left;
}

.project-description {
    word-spacing: 0.8px;
    letter-spacing: -0.2px;
}

.project-image{
    height: 150px;
    width: 250px;
    cursor: pointer;
    border-radius: 5px;
}

.tech-stack-container{
    display: flex;
}

.tech-stack{
    margin-right: 10px;
    font-size: 12px;
    font-weight: 600;
    color: rgba(198, 198, 198,0.8);
    transition: 0.3s;
}

.project-card:hover .tech-stack{
    color: #6d6d6d
}

.repo-link{
    margin-left: 20px;
}

.repo-logo{
    color: rgba(0, 0, 0, 0.8);
}

.repo-logo:hover{
    color: rgba(0, 0, 0, 0.6);
}








@media only screen and (max-width: 500px){
    nav{
        display: flex;
        align-items: center;
        justify-content: center;
        float: none;
        height: 22px;
    }
    .section{
        width: 90%;
    }
    .main-container{
        flex-direction: column-reverse;
        justify-content: space-evenly;
    }
    .name-text{
        text-align: center;
        font-size: 28px;
    }

    .intro-text{
        font-size: 18px;
    }

    .project-card{
        flex-direction: column;
    }

    #work{
        min-height: fit-content;
        height: fit-content;
    }
}
header {
    position: fixed;
    width: 100%;
    background: rgba(255, 255, 255, 0.8);
    padding: 10px 0;
    z-index: 1;
    transition: all ease-in-out 0.5s;
}

.green-nav {
    background-color: lawngreen;
}

header:after {
    content: "";
    display: block;
    clear: both;
}

nav {
    float: right;
    padding: 0 10%;
}

nav a {
    font-size: 1rem;
    margin: 5px 10px;
    color: #484848;
    text-decoration: none;
    transition: 0.3s;
    padding-bottom: 2px;
    font-weight: 500;
    position: relative;
    padding: 2px 5px;
    cursor: pointer;
    user-select: none;
    -webkit-user-select: none;
    -moz-user-select: none;
}

nav a::after {
    position: absolute;
    bottom: 0;
    left: 0;
    content: '';
    height: 1px;
    width: 100%;
    background-color: #484848;
    transform: scaleX(0);
    transition: 0.5s;
    transform-origin: center;
}


nav a:hover::after {
    transform: scaleX(1);
}

* {
    margin: 0;
    padding: 0;
    scroll-behavior: smooth;
}

:root{
    --primary-text-color: #000;
    --para-text-color: #323232;
}

body {
    font-family: 'Montserrat', sans-serif;
    font-weight: 400;
    /* scrollbar-color: rgba(0, 0, 0, .5);
    scrollbar-track-color: #f1f1f1; */
}

a {
    text-decoration: none;
    color: #000;
}



/*-------- Custom scroll bar and selection -----*/

@media only screen and (min-width: 600px) {
    ::-webkit-scrollbar {
        width: 7px;
    }

    ::-webkit-scrollbar-thumb {
        border-radius: 4px;
        background-color: rgba(0, 0, 0, .5);
        box-shadow: 0 0 1px rgba(255, 255, 255, 0.5);
    }

    ::-webkit-scrollbar-thumb:hover {
        background: rgba(0, 0, 0, .6);
    }

    ::-webkit-scrollbar-track {
        background: #f1f1f1;
    }
}

::selection {
    background-color: rgb(78, 81, 83);
    color: #fff;
}


/* ------- back to top btn */

#bttBtn-wrapper {
    position: absolute;
    bottom: 50px;
    right: 50px;
    background-color: grey;
    border-radius: 50%;
    height: 40px;
    width: 40px;
    cursor: pointer;
}

.btnWrapperHidden {
    transform: scale(0);
    transform-origin: center;
    transition: 300ms;
}

.btnWrapperShow {
    transform: scale(1) rotate(360deg);
    transform-origin: center;
    transition: 300ms;
}

#bttBtn {
    width: 15px;
    height: 15px;
    border-radius: 2dpx;
    border-left: 3px solid;
    border-top: 3px solid;
    transform: rotate(45deg);
    margin: auto;
    margin-top: 11px;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="google-site-verification" content="x2GVvk7gy3nGrRmARofMXwMNs9MIXvu2BcyEs7RH8KQ" />
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,500,700&display=swap" rel="stylesheet">
    <meta name="Description" content="Name: Rajiv, thoughtlessmind, Profession: Web developer, Country: India, ">
    <script src="https://kit.fontawesome.com/09ef7cae5b.js" crossorigin="anonymous"></script>
    <script defer src="index.js"></script>
    <link rel="stylesheet" href="CSS/style.css">
    <!-- Chrome, Firefox OS and Opera -->
    <meta name="theme-color" content="#4285f4">
    <!-- Windows Phone -->
    <meta name="msapplication-navbutton-color" content="#4285f4">
    <!-- iOS Safari -->
    <meta name="apple-mobile-web-app-status-bar-style" content="#4285f4">
    <title>Rajiv</title>
</head>

<body>
    <div id="top"></div>
    <header>
        <nav>
            <a onclick="moveToWork()">Work</a>
            <a onclick="moveToAbout()">About</a>
            <a onclick="moveToContact()">Contact</a>
        </nav>
    </header>

    <main>
        <div class="main-container section" id="main-section">
            <!-- <img src="" alt="avatar" class="avatar" style="height: 200px;width: 200px; background-color: wheat;align-self: center;"> -->
            <div class="right-container">
                <div class="text-container">
                    <h1 class="name-text">Rajiv</h1>
                    <p class="intro-text">
                        Hey, I'm a web developer based in New Delhi.
                        <br>
                        I build things using <b>Javasript</b>.
                    </p>
                </div>
            </div>

            <div class="left-container">
                <div class="left-image">

                </div>

                <div class="social-link-container">
                    <a href="https://github.com/thoughtlessmind" target="_blank" id="github" class="social-link">
                        <i class="fab fa-github social-logo"></i>
                    </a>
                    <a href="https://www.linkedin.com/in/thoughtlessmind/" target="_blank" id="linkedin"
                        class="social-link">
                        <i class="fab fa-linkedin social-logo"></i>
                        </svg>
                    </a>
                </div>
            </div>
        </div>


        <!-- Work Section -->
        <div id="work" class="work-section section">
            <h2>Work</h2>

            <div class="project-card">
                <div class="left-side-card">
                    <div>
                        <a href="https://thoughtlessmind.github.io/Vegan-store" target="_blank" class="project-link">
                            <h3 class="project-name">
                                Vegan Store
                            </h3>
                        </a>
                        <p class="project-description">
                            It is a dummy vegan food store website. <br>
                            This is a fully responsive website made using CSS Flexbox and Grids
                        </p>
                    </div>
                    <div title="techstack used" class="tech-stack-container">
                        <p class="tech-stack html-logo">HTML</p>
                        <p class="tech-stack css-logo">CSS</p>
                        <a title="open repo" href="" class="repo-link">
                            <i class="fas fa-code repo-logo"></i>
                        </a>
                    </div>
                </div>
                <div class="right-side-card">
                    <img src="/assets/vegan-store-img.jpg" title="Visit Page" alt="Vegan store" class="project-image"
                        id="vegan-store-image">
                </div>
            </div>

            <div class="project-card">
                <div class="left-side-card">
                    <div>
                        <a href="https://thoughtlessmind.github.io/Vegan-store" target="_blank" class="project-link">
                            <h3 class="project-name">
                                Vegan Store
                            </h3>
                        </a>
                        <p class="project-description">
                            It is a dummy vegan food store website. <br>
                            This is a fully responsive website made using CSS Flexbox and Grids
                        </p>
                    </div>
                    <div title="techstack used" class="tech-stack-container">
                        <p class="tech-stack html-logo">HTML</p>
                        <p class="tech-stack css-logo">CSS</p>
                        <a title="open repo" href="" class="repo-link">
                            <i class="fas fa-code repo-logo"></i>
                        </a>
                    </div>
                </div>
                <div class="right-side-card">
                    <img src="/assets/vegan-store-img.jpg" title="Visit Page" alt="Vegan store" class="project-image"
                        id="vegan-store-image">
                </div>
            </div>

        </div>

        <!-- about section -->

        <div id="about" class="about-section section">
            <h2>About</h2>
            <div class="education-container">
                <h3>Education</h3>
            </div>
        </div>

        <!-- Back to top btn -->
        <div onclick="moveToTop()" id="bttBtn-wrapper">
            <div id="bttBtn">

            </div>
        </div>
    </main>
</body>

</html>

Sign up to request clarification or add additional context in comments.

6 Comments

no. the repo doesn't contain the code for adding the scroll eventListener. try adding an eventListener in the above js code you've posted from the repo. :)
I fixed it. refer to the answer
Yeah. I tried it on codepen, and it working well as expected but on localserver on chrome it is not working (nothing is logged as expected). Here is the link codepen.io/thoughtlessmind/pen/vYNmebE?editors=1111
Try changing window.onscroll to documen.onscroll of my answer. (Height removed, onload added)
oh yeah.. Thank you very much, after removing height from main it has started working. :)
|
0

Try this one

const main = document.querySelector('main');
// main.onscroll = logScroll;

main.addEventListener('scroll', logScroll)

function logScroll(e) {
  console.log(`Scroll position: ${e.target.scrollTop}`);
  if(e.target.scrollTop  == 761){
      console.log('About Page is Reached');
  }
}

Note for target.onscroll

Only one onscroll handler can be assigned to an object at a time. For greater flexibility, you can pass a scroll event to the EventTarget.addEventListener() method instead.

As explained here https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onscroll

As I understand here in my code above, the target.scrollTop will only works when you have selected a valid target in your document object. In this case as I inspect your html markup you have wrapped your whole sections to a main tag.

Now that's it, I tried to get your main tag and add an eventListener to it, and it works to me. Hope this also works to you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.