Sorry, but I am a complete noob with JS. I am using Bootstrap to try build my first website.
The website has a fixed top navbar
. I want to change the navbar
‘s border-bottom properties when it reaches the bottom of the header div
(about 480/500px down the page).
Currently the border-bottom is white, but I want to change it to blue when scrolled beyond a certain point (bottom of header) and then change back to white if scrolled back up again. The effect I want is the appearance of the fixed nav
‘picking up’ the bottom border of the banner section when it scroll’s past.
I have given the navbar div an id of id="n1"
, and created a class .navbar1{border-bottom: 1px solid rgba(46,152,255,1)!Important;}
to add to override the existing css.
I am not using jQuery because I don’t use much JS and I don’t want to call it just for a few things – it is a big file. I have tried various things without any success. Probably because they relied on jQuery? I don’t know. For example, the last one was:
$(window).scroll( function(){ if($(window).scrollTop() > 50) $("n1").addClass("navbar1"); else $("n1").removeClass("navbar1"); });
Anyway, I was hoping someone may be able to help me with the plain/pure JS to change the attribute properties as described. Thank you in advance for any assistance.
EDIT:
This has been kindly answered below. But given some comments, I thought it might be useful to clarify my use of JS: My website requires very little JS functionality so I have chosen to inline my JS, rather than call an external JS file or files – such as jquery.js
and bootstrap.js
which are relatively large files.
Although I lose the benefit of caching the JS, and my HTML is slightly larger, I am happy to do that because in my case I feel those losses are more than made up for the increased initial page load speed from:
- not having to make additional http requests,
- not having to load relatively large files.
It is certainly not for everyone, but I feel that it suits my case. Having said that, when all is done and my website is up and running I will probably do some testing to see whether a custom external JS file is better again. Basically, I am only using Bootstrap for its CSS functionality, not its JS functionality. I hope that makes sense.
Advertisement
Answer
This demo may help you! It doesn’t use jQuery.
Here is the javascript code:
window.onscroll = function() { var nav = document.getElementById('nav'); if ( window.pageYOffset > 100 ) { nav.classList.add("navbar1"); } else { nav.classList.remove("navbar1"); } }