Reputation: 1
I'm currently trying to change the color of my header [id ='site-header']
once the page starts being scrolled down. I'm trying to add a class to the header after the window is scrolled more than 100px. I'm developing the website with Wordpress, and for some reason the code works when I have Wordpress' customizer open, but it won't work otherwise.
HTML
<body class="home-page bp-nouveau home page-template-default page page-id-5 logged-in admin-bar no-customize-support geodir_advance_search geodir-page sd-common sd sd-homepage no-js gd-map-auto">
<div id="ds-container" >
<header id="site-header" class="site-header " role="banner" style="">
<div class="container">
Javascript
<script type="text/javascript">
jQuery(document).scroll(function( $ ){
if(jQuery(document).scrollTop() > 100) {
document.getElementById('#site-header').addClass('active');
} else {
//remove the background property so it comes transparent again (defined in your css)
document.getElementById('#site-header').removeClass('active');
}
});
</script>
Any idea why this might be happening? The link for the website is this.
Upvotes: 0
Views: 1208
Reputation: 177
Below code should be work for you. Replace your current jQuery/javascript code with below one.
jQuery(document).ready(function(){
jQuery(window).scroll(function(){
var sTop= jQuery(this).scrollTop();
if(sTop > 100){
jQuery('#site-header').addClass('active');
} else {
jQuery('#site-header').removeClass('active');
}
});
})
Upvotes: 1
Reputation: 18249
I see at least 3 problems with this code:
1) the ID of the element is site-header
- not #site-header
, which is just the CSS selector.
2) You are mixing jQuery with vanilla JS - which isn't wrong in itself, but there is no addClass
method on the object returned by calls to getElementById
. You need to either call classList.add(...)
on this "element" object, or (easier, since you're using jQuery already) just use jQuery: jQuery('#site-header').addClass('active');
(I suspect this jQuery-or-not confusion is what caused the stray "#" in your vanilla JS code.
3) Best practice is to wrap things like this in a callback function passed to jQuery's document.ready()
- otherwise the event listener may not even be created. (I would assume the document
object probably does exist at the point this code is run, so this may not matter, but it's still best practice.)
Upvotes: 2