Reputation: 69
Hello i am trying to stick my header in the screen when i scroll from top to bottom. This js function was supposed (following yt tutorial) to stick my header changing my nav color but it isn't working.
<script type="text/javascript">
window.addEventListener('scroll', function(){
var header = document.querySelector('header');
header.classList.toggle('sticky', window.scrollY > 0);
});
</script>
this is my CSS
header{
position: fixed; /*fijamos el header a la pantalla*/
top:0; /*ayudamos a que el header quede fijo*/
left:0; /*ayudamos a que el header quede fijo*/
width: 100%; /*ancho del header*/
padding: 2.500em 6.250em; /*40px arriba abajo y 100px a los lados*/
z-index: 100; /*orden de elemento posicionado*/
display: flex; /*caja flexible*/
justify-content: space-between; /*separamos los elementos de la caja*/
align-items:center; /*centramos los elementos*/
transition: 0.5s;
}
header .sticky{
background: #fff;
padding: 20px 100px;
box-shadow: 0 5px 20px rgba(0,0,0,0.1);
}
header .logo{
color: #fff;
font-size: 1.5em; /*24px*/
text-transform: uppercase;
text-decoration: none;
font-weight: 700;
letter-spacing: 0.125em; /*2px - espacio entre letras*/
}
header .sticky .logo{
color: #111;
}
header ul{
position: relative;
display:flex;
}
header ul li{
position:relative;
list-style: none;
}
header ul li a{
position: relative;
display: inline-block;
margin: 0 0.938em; /*0 arriba abajo y 15px a los lados*/
color: #fff; /*color texto*/
text-decoration: none; /*quitamos subrayado*/
}
header .sticky ul li a{
color: #111;
}
Originally my header is black with white text so when i scroll from top to bottom it is supposed to stick changing my white text to black so i can appreciate it when i nav in my sections with white background...
Viewing the html dev tools that js function it's getting called when i scroll image but nothing is happening, it isn't even changing the text color/background
my HTML
Upvotes: 1
Views: 1735
Reputation: 311
Please notice that element .class
and element.class
are different.
as you are targeting the header element in the function I can assume your problem is that you are looking for an element with .sticky
class which is a descendant of header when you select header .sticky
; but you need the header itself.
header .sticky {
background: #fff;
padding: 20px 100px;
box-shadow: 0 5px 20px rgba(0,0,0,0.1);
}
consider using header.sticky
to select the header with the .sticky
class. you have to fix other selectors too.
header.sticky {
background: #fff;
padding: 20px 100px;
box-shadow: 0 5px 20px rgba(0,0,0,0.1);
}
have a look at CSS Selectors for more selector patterns.
Upvotes: 1