Reputation: 87
I'm using bootstrap grayscale theme for my project and It has a navbar that collapses on scroll, or if I go to a link that's on the same page (#download etc.)
The problem is when I go to anchor link from some other page, than navbar doesn't collapse until I scroll.
I guess the solution is in adding the line in java script, but I really don't know what to add since I don't know java. :-(
// jQuery to collapse the navbar on scroll
$(window).scroll(function() {
if ($(".navbar").offset().top > 50) {
$(".navbar-fixed-top").addClass("top-nav-collapse");
} else {
$(".navbar-fixed-top").removeClass("top-nav-collapse");
}
});
Please, help. :) :-*
Upvotes: 3
Views: 11935
Reputation: 83
You can also use :
$(document).ready(function() {
function checkOffset() {
$(".navbar").removeClass("show");
}
// Run function when scrolling
$(window).scroll(function() {
checkOffset();
});
// Run function on Clicking
$(window).click(function() {
checkOffset();
});
});
This will help with navbar collapse on mobile devices.
Upvotes: 2
Reputation: 4024
You need to run the check when the page loads as well as when the window is scrolled, you can do that without duplicating any code by putting the logic that checks the offset of the page in a function and running it from both document ready and window scroll.
$(document).ready(function() {
// Put your offset checking in a function
function checkOffset() {
if ($(".navbar").offset().top > 50) {
$(".navbar-fixed-top").addClass("top-nav-collapse");
}
else {
$(".navbar-fixed-top").removeClass("top-nav-collapse");
}
}
// Run it when the page loads
checkOffset();
// Run function when scrolling
$(window).scroll(function() {
checkOffset();
});
});
Edit:
I believe you could shorten this even more by replace the checkOffset function with the following:
// Put your offset checking in a function
function checkOffset() {
$(".navbar-fixed-top").toggleClass("top-nav-collapse", $(".navbar").offset().top > 50);
}
I haven't tested this, but as long as the second parameter in toggleClass returns a boolean it'll either add or remove the class depending on the offset of the page without needing an if statement.
Upvotes: 5
Reputation: 362840
You should be able to do something as simple as this..
$('.navbar-collapse ul li a').click(function() {
/* always close responsive nav after click */
$('.navbar-toggle:visible').click();
});
It's not Java, it's JavaScript which is easily added to your html page using script tags.
Upvotes: 1