To avoid confusion and before you read on, this is NOT "how many pixels down" but at, for example, <section id="smaller">
then it would add a class. I'm new to javascript so please take that with a grain of salt. Thanks.
I'm trying to change the header by adding a new attribute class to the header file. Following code works ok on desktop when your width never changes but what if your on a phone and your design is responsive? Yes, this is exactly why I need your help. I tried so many thing already and don't know how to get this setup like I want. I am new to web dev and this is one of my first few websites.
My code right now:
function init() {
window.addEventListener('scroll', function (e) {
var distanceY = window.pageYOffset || document.documentElement.scrollTop, header = document.querySelector("header");
if (distanceY > 606) {
header.setAttribute("class", "smaller");
} else {
header.removeAttribute("class");
}
});
}
window.onload = init();
Couple of things I need to clear up, and/or if you're a little confused:
- the header is the actual
<header>
not a div with a header class or id. - like I said, this does work right now but is only useful for a fixed width for every screen size
- I'm including this code on a js file which is linked just before the ending of the
<body>
tag. - "606" being the length down the page in pixels when the change happens
Is there a way to add an attribute to the header when you reach a certain place on the web page? If anyway could give me some guidance, that would be great. Thanks a bunch for reading this and enjoy the rest of your day. :)