According to Bootstrap 3 docs I have added following attributes to a navbar:
<nav class="navbar no-margin-bottom" data-spy="affix" data-offset-top="90" >
...
</nav>
After scrolling down the page Bootstrap 4 is not adding class to navbar which is affix. Can anyone tell me how to solve this problem? Bootstrap.js and jQuery.js are working.
Although the affix is removed from Bootstrap in version 4. However, you can achieve your goal through this jQuery Code:
$(window).on('scroll', function(event) {
var scrollValue = $(window).scrollTop();
if (scrollValue == settings.scrollTopPx || scrollValue > 70) {
$('.navbar').addClass('fixed-top');
}
});
Update Bootstrap 4
The docs recommend the sticky polyfill, and the recommended ScrollPos-Styler doesn't really help with scroll position (you can easily define an offset).
I think it's easier to use jQuery to watch the window scroll and change the CSS accordingly to fixed...
var toggleAffix = function(affixElement, wrapper, scrollElement) {
var height = affixElement.outerHeight(),
top = wrapper.offset().top;
if (scrollElement.scrollTop() >= top){
wrapper.height(height);
affixElement.addClass("affix");
}
else {
affixElement.removeClass("affix");
wrapper.height('auto');
}
};
$('[data-toggle="affix"]').each(function() {
var ele = $(this),
wrapper = $('<div></div>');
ele.before(wrapper);
$(window).on('scroll resize', function() {
toggleAffix(ele, wrapper, $(this));
});
// init
toggleAffix(ele, wrapper, $(window));
});
Bootstrap 4 affix (sticky navbar)
EDIT: Another solution is to use this port of the 3.x Affix plugin as a replacement in Bootstrap 4..
http://www.codeply.com/go/HmY7DLHLkI
Related: Animate/Shrink NavBar on scroll using Bootstrap 4
From the bootstrap v4 documentation:
Dropped the Affix jQuery plugin. We recommend using a position: sticky polyfill instead. See the HTML5 Please entry for details and specific polyfill recommendations.
If you were using Affix to apply additional, non-position styles, the polyfills might not support your use case. One option for such uses is the third-party ScrollPos-Styler library.
To build on Anwar Hussain's answer. I found success with this:
$(window).on('scroll', function (event) {
var scrollValue = $(window).scrollTop();
if (scrollValue > 120) {
$('.navbar').addClass('affix');
} else{
$('.navbar').removeClass('affix');
}
});
This will apply the class to the navbar when scrolling down, but will also remove the class when scrolling back up. Previously, when scrolling back up, the applied class would stay applied to the navbar.
As per Vucko's quote within the Mirgation docs, ScrollPos-Styler library suited me quite well.
Include the .js ScrollPos-Styler (scrollPosStyler.js) file to your page.
Find the relevant <div> you wish to make 'sticky'
<nav class="navbar navbar-toggleable-md">
Apply sps sps--abv class
<nav class="navbar navbar-toggleable-md sps sps--abv">
Add .css styles you wish to have triggered once the element has become sticky (As per the demo page.
/**
* 'Shared Styles'
**/
.sps {
}
/**
* 'Sticky Above'
*
* Styles you wish to apply
* Once stick has not yet been applied
**/
.sps--abv {
padding: 10px
}
/**
* 'Sticky Below'
*
* Styles you wish to apply
* Once stick has been applied
**/
.sps--blw {
padding: 2px
}
$(window).on('scroll', function (event) {
var scrollValue = $(window).scrollTop();
var offset = $('[data-spy="affix"]').attr('data-offset-top');
if (scrollValue > offset) {
$('[data-spy="affix"]').addClass('affix-top');
var width = $('[data-spy="affix"]').parent().width();
$('.affix-top').css('width', width);
} else{
$('[data-spy="affix"]').removeClass('affix-top');
}
});
For the users who are looking for an answer in pure Javascript, this is how you can do it by using pure Javascript:
window.onscroll = (e) => {
let scrollValue = window.scrollY;
if (scrollValue > 120) {
document.querySelector('.navbar').classList.add('affix');
} else{
document.querySelector('.navbar').classList.remove('affix');
}
}
With bootstrap 4 there is special class for that.
Try removing the data-spy="affix" data-offset-top="90" attributes, and just add 'sticky-top'.
documentation
After trying every solution I could find (and being aware that affix was removed from bootstrap 4), the only way I could get the desired sticky results I needed was to use sticky-kit.
This is s really simple jQuery plugin that was easy to set-up.
Just include the code in your project and then assign the element you want to stick with
$("#sidebar").stick_in_parent();
simple use class fixed-top in bootstrap 4 and use addClass and removeClass
$(window).on('scroll', function(event) {
var scrollValue = $(window).scrollTop();
if ( scrollValue > 70) {
$('.navbar-sticky').addClass('fixed-top');
}else{
$('.navbar-sticky').removeClass('fixed-top');
}
});
Related
I want remove .bg-light from nav element at 400px and more scrolls
<nav id="my-nav" class="bg-light navbar text-info"> change my background color</nav>
I know it's an easy task with jQuery but is it possible to do it with vanilla js?
Thanks for spending time on my question I will be glad to see opinion
First, we start by grabbing the "nav" element using the ID.
Then setting our Y-axis's offset.
Attach a listener to the window object.
On scroll, compare the current position to our desired offset.
const navBar = document.getElementById("my-nav");
const offset = 400;
window.addEventListener("scroll", () => {
if (window.scrollY >= offset){
navBar.classList.remove("bg-light")
} else {
navBar.classList.add("bg-light")
}
})
Yes, its possible with Vanilla JavaScript, use the "scroll" event handler to get the info. As the users moves through the site it will return the Y axis position in pixels. By using an if statement remove or add the bg-light class, like so:
let nav = document.getElementById("my-nav");
window.addEventListener("scroll", (e) => {
if(this.scrollY > 400){ nav.classList.remove('bg-light') }
else{
nav.classList.add('bg-light')
}
});
*{padding:5px}
html{height:3000px;font-size:20px}
.bg-light{background-color: #F8F8F8!important; color:black!important;}
.navbar{position:fixed;background-color:blue; color:white;}
<nav id="my-nav" class="bg-light navbar text-info"> Change my background color at scrollY 400px</nav>
I'm currently using the onepage-scroll.js (https://github.com/peachananr/onepage-scroll) plug-in on my website to scroll through the homepage. When scrolling past the first "slide" I would also like to add a class (sticky) to my header to change some CSS. I've tried the code below, but I can't seem to get it working and I'm kinda in the dark here on how to make this solution work.
var header = $("header");
$("#sliders").scroll(function() {
var scroll = $('#sliders').scrollTop();
console.log(scroll);
if (scroll >= 50) {
header.addClass("sticky");
} else {
header.removeClass("sticky");
}
});
Try to make it on document ready.
Down only my example worked code on onepage-scroll.js
$(document).ready(function(){
$(".main").onepage_scroll({
sectionContainer: ".sectionscroll",
responsiveFallback: 600,
loop: true,
afterMove:function (index){
if ((index == 2)||(index == 3)){
$('#main').addClass('darktheme');
}else{
$('#main').removeClass('darktheme');
}
}
});
//$(".main").moveTo(2);
$(".btn-list-bottom").click(function(){$(".main").moveTo(4)});
});
All you section must have the same class.
I'm trying to adapt this JSFiddle to make the menu button on my website hide when I'm at the top of the page and show when I start scrolling down.
I modified the JS to match the CSS on my site. Then I placed it in tags in the head of my page
var $scb = $('<div class="toggle-menu-wrap"></div>');
$('.top-header').append($scb);
var $ccol = $('.content');
$ccol.scroll(function(){
$scb.stop(true,true).fadeTo(500, $ccol.scrollTop() > 10 ? 1 : 0);
});
However, it still doesn't work. Am I making a mistake in how I'm modifying the JS to fit my CSS?
You can include the toggle-menu-wrap element in your HTML from the start. There is no need to insert it using JS.
Write the one line of CSS you need, which is to hide the element from the beginning
.toggle-menu-wrap {
display: none;
}
Your version of jQuery uses 'jQuery' instead of '$' to reference itself. I would also re-write your JS like:
jQuery(document).ready(function() {
fadeMenuWrap();
jQuery(window).scroll(fadeMenuWrap);
});
function fadeMenuWrap() {
var scrollPos = window.pageYOffset || document.documentElement.scrollTop;
if (scrollPos > 300) {
jQuery('.toggle-menu-wrap').fadeIn(300);
} else {
jQuery('.toggle-menu-wrap').fadeOut(300);
}
}
Like #murli2308 said in the comments above, you need to attach a scroll event listener to the window:
$(document).ready(function () {
var $scb = $('<div class="scroll-border"></div>');
$('.above').append($scb);
var $ccol = $('.content');
$(window).scroll(function(){
$scb.stop(true,true).fadeTo(500, $ccol.scrollTop() > 10 ? 1 : 0);
});
})
Wrapping your code in $(document).ready() would also be a good idea.
The reason $ccol.scroll(function() { ... works in that fiddle is because of the CSS:
.content{
height: 200px;
width: 200px;
overflow: auto;
}
Notice overflow: auto;. This causes that specific div to be scrollable. However, on your website, you scroll the entire page, not $ccol. This means the event handler will never fire a scroll event (since $ccol will never scroll).
You might have forgotten to link Jquery.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
Link this inside your head tag incase.....
This should do the job:
$(window).scroll(function(e){
if ($(this).scrollTop() > 0) {
$(".your_element").css("display", "block");
} else {
$(".your_element").css("display", "none");
}
});
I'm trying to use the affix function to attach a header to the top of the screen, but have it attached only for a portion of the page. It should detach (and scroll up along with the content) when the user scrolls past a certain point.
I'm using the script from this jsfiddle.
What I'm trying right now is this:
$('#nav-wrapper').height($("#nav").height());
$('#nav').affix({
offset: $('#nav').position()
});
$('#nav').detached({
offset: $('#bottom').position()
});
With the .detached class like so:
.detached { position: static; }
Can't get this to work. Any suggestions?
Twitter Bootstrap affix module doesn't have that option. But, I've used many times hcSticky, it is awesome. Take a look, it's simply to use and works very well.
You can write the logic in a function, and pass it to affix as offset.top.
Try
var navHeight = $("#nav").height();
var detachTop = $("#detach").offset().top;
var navTop = $("#nav-wrapper").offset().top;
$('#nav-wrapper').height(navHeight);
$('#nav').affix({
offset : {
top : function() {
if ((navHeight + $(window).scrollTop()) > detachTop) {
return Number.MAX_VALUE;
}
return navTop;
}
}
});
Fiddle is here.
Another option which might work for you: http://jsfiddle.net/panchroma/5n9vw/
HTML
<div class="header" data-spy="affix">
affixed header, released after scrolling 100px
</div>
Javascript
$(document).ready(function(){
$(window).scroll(function(){
var y = $(window).scrollTop();
if( y > 100 ){
$(".header.affix").css({'position':'static'});
} else {
$(".header.affix").css({'position':'fixed'});
}
});
})
Good luck!
I've found a great tutorial to detach a navigation from the page to keep it static when you scroll using Javascript (http://code.stephenmorley.org/javascript/detachable-navigation/).
However, I'd like to implement this on more than one nav div.
I assume it's adding another class name to document.getElementById('navigation').className but I can't get the right syntax
Here is the code:
/* Handles the page being scrolled by ensuring the navigation is always in
* view.*/
function handleScroll(){
// check that this is a relatively modern browser
if (window.XMLHttpRequest){
// determine the distance scrolled down the page
var offset = window.pageYOffset
? window.pageYOffset
: document.documentElement.scrollTop;
// set the appropriate class on the navigation
document.getElementById('navigation').className =
(offset > 104 ? 'fixed' : '');
}
}
// add the scroll event listener
if (window.addEventListener){
window.addEventListener('scroll', handleScroll, false);
}else{
window.attachEvent('onscroll', handleScroll);
}
You will have to call getElementById() for each ID. The Method is only designed to get exactly one element (or zero, if the ID isn't found).
Assuming, you have two navigation divs, left and right, like this:
<div id="navigationLeft">
<ul>
<!-- Navigation entries -->
</ul>
</div>
<!-- Maybe some content or whatever? -->
<div id="navigationRight">
<ul>
<!-- Navigation entries -->
</ul>
</div>
Then your Javascript line in question would look like this:
// set the appropriate class on the navigation
document.getElementById('navigationLeft').className = (offset > 104 ? 'fixed' : '');
document.getElementById('navigationRight').className = (offset > 104 ? 'fixed' : '');
// or, shorter but less readable (i think)
document.getElementById('navigationLeft').className
= document.getElementById('navigationRight').className
= (offset > 104 ? 'fixed' : '');
If this does not yet answer your question, please feel free to add some relevant HTML-Code to your question.
[Update: Example]
This is not recommended you should replace id with classes and use that in a loop to set the value:
HTML:
<div class="navigation">
<p>test 1</p>
</div>
<div class="navigation">
<p>test 2</p>
</div>
Javascript:
divs = document.getElementsByClassName('navigation');
for(i = 0; i < divs.length; i++) {
var div = divs[i];
var divClassName = div.className;
if(divClassName.indexOf('fixed') != -1 && offset > 104) {
divClassName.replace(' fixed','');
} else {
divClassName += ' fixed';
}
}
I think that will do the trick :-)
Greetings!
Gonzalo G.
you shouldnt have multiple items on a page with the same ID, ID's are meant to be unique...if you want to capture multiple items you should use:
<div class="navigation"></div>
var nodes = document.getElementsByClassName('navigation')
...if not using jquery, otherwise do something like
var nodes = $('.navigation')
which will get you yor nav bars, then check to see if that node is also "fixed" ( a node can have more than one css class )
(nodes[i].indexOf("navigation") >= 0)
if using jquery, you can use .hasClass('fixed') )
nodes[i].hasClass('fixed')
...your current problem is that it cant add className to navigation because there are two of them and youre not specifying which one you'd like to use.
If you want this to happen in two navigation div's, consider putting them both into one div and call it nav and set a style on it (this depends on your design)
All id's on an element must be unique.
One solution so that you can do a simple change would be to change the CSS file to something like this:
.navigation{
position:absolute;
top:120px;
left:0;
}
.navigationFixed{
position:fixed;
top:16px;
}
And define the Div's vis this:
<div class="navigation">
<!-- your navigation code -->
</div>
And then edit the JavaScript to something along the lines of this:
/* Handles the page being scrolled by ensuring the navigation is always in
* view.
*/
function handleScroll(){
// check that this is a relatively modern browser
if (window.XMLHttpRequest){
divs = document.getElementsByClassName('navigation');
for(i = 0; i < divs.length; i++) {
// determine the distance scrolled down the page
var offset = window.pageYOffset
? window.pageYOffset
: document.documentElement.scrollTop;
divs[i].className =
(offset > 104 ? 'navigationFixed' : 'navigation');
}
}
}
// add the scroll event listener
if (window.addEventListener){
window.addEventListener('scroll', handleScroll, false);
}else{
window.attachEvent('onscroll', handleScroll);
}