Deactivate the page scroll at a specific time

Asked

Viewed 57 times

1

I made a kind of carousel with CSS and a little bit of Javascript with some images and as I use the mouse scroll on top of the images the images move to the side, the problem is that the page also goes down as I use the scroll to pass the images. I’m a beginner in programming and I have no idea how to disable page scroll while mouse is on top of images.

The code of the HTML images:

<div id="galeria">
    <div id="itens">
        <div class="item">
            <img src="imagens/Chrysanthemum.jpg">
        </div>
        <div class="item">
            <img src="imagens/Desert.jpg">
        </div>
        <div class="item">
            <img src="imagens/Tulips.jpg">
        </div>
        <div class="item">
            <img src="imagens/Koala.jpg">
        </div>
        <div class="item">
            <img src="imagens/Penguins.jpg">
        </div>
    </div>
</div>

The CSS code:

#galeria{
    width: 100%;
    height: 100%;
}

#itens{
    display: flex;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    scroll-behavior: smooth;
    scroll-snap-type: x mandatory;
}

.item{
    flex: none;
    width: 100%;
    height: 250px;
    scroll-snap-align: start;
    pointer-events: none;
}

img{
    width: 100%;
    height: 98%;
    object-fit: cover;
}

The code of Javascript:

document.querySelector("#itens").addEventListener("wheel", event => {

            if(event.deltaY > 0){
                event.target.scrollBy(300, 0)
            }else{
                event.target.scrollBy(-300, 0)
            }

        });

1 answer

1


Try the following:

document.querySelectorAll("#itens img").forEach(img => {
  img.addEventListener('mouseenter', ()=> document.body.style.overflow = 'hidden')
  img.addEventListener('mouseleave', ()=> document.body.style.overflow = null)
})

This is a simple but straightforward solution to your question.

First, if you want to remove the scroll only for the images, you should select them, so I added the img in the querySelectorAll.

"overflow: hidden" is one of the simplest ways to remove scroll and this works on body.

To return to normal, simply set the definition of overflow. (simple form)

And for that to work legal, the appropriate events are mouseenter and mouseleave.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.