I want to create an action using HTML, CSS and JS, when you scroll horizontally on a div.
This code which I found on w3Schools is what I was looking for, but I can not modify it to accept horizontal scroll. Basically it needs to indicate which image is on screen (1 or 2) using lets say dots.
window.onscroll = function() {
myFunction()
};
function myFunction() {
if (document.documentElement.scrollTop > 50) {
document.getElementById("myP").className = "test";
} else {
document.getElementById("myP").className = "";
}
}
body {
font-size: 20px;
height: 1500px;
}
#myP {
position: fixed;
}
.test {
background-color: yellow;
}
<h1>The onscroll Event</h1>
<p id="myP">
If you scroll 50 pixels down from the top of this page, the class "test" is added to this paragraph. Scroll up again to remove the class.
</p>
I tried to modify the code from previous link and some others, but without success. This code seem to be the closest to what I need.
3
Answers
To make this work horizontally make the page content wider than the viewport, in the example I simply set its
width
to5000px
, and changescrollTop
in the JS logic toscrollLeft
.Also note that the code quality from W3Schools is very rarely of good quality. It’s for this reason I would strongly suggest you avoid them and use a better resource, such as MDN.
To improve the quality of the code in your example you can avoid using
onscroll
or any of the other event properties. UseaddEventListener()
instead. In addition use theclassList
collection to add/remove/toggle classes on elements.To highlight the text when horizontally scrolling, you firstly adjust the width:
This makes sure there is enough space to scroll horizontally.
After you have done that, to apply the effect when scrolling, instead of
scrollUp
you usescrollLeft
like this:This should highlight the text when scrolling horizontally 50 pixels.
to achieve horizontal scrolling detection and indicate which image is currently on the screen, you’ll need to make a few adjustments to your code
In this code:
color changes to yellow when the corresponding image is in view.